Menu click function doesn't work first time

Hi!

Next function doesn’t work first time when menu item is clicked but works after that. It is located just before </body> tag. It puts the ‘current’ selector in the selected menu item. Any idea why it doesn’t work first time? I’m quite beginner with javascript.

<script type="text/javascript">
(function ($, NAME) {	
    var nav = $('ul#primary-menu');		
    nav.find('a').on('click',function(e){		
	
	var $this = $(this),
            $targetContent;
						
    $this.closest('[id="primary-menu"]').find('a').removeClass('current');
    $this.addClass('current');		
       
    });
	
})(jQuery);

</script>

If you are running this immediately in the HTML, it is likely that the Hype document has not loaded yet. You’ll either want to insert the code in an On Scene Load action that runs javascript, or setup an event listener/callback for the HypeDocumentLoad event if you’re going to but the code in the head HTML. It would look something like:

<script>

	function myCallback(hypeDocument, element, event) {
    	(function ($, NAME) {	
			var nav = $('ul#primary-menu');		
			nav.find('a').on('click',function(e){		
	
			var $this = $(this),
					$targetContent;
						
			$this.closest('[id="primary-menu"]').find('a').removeClass('current');
			$this.addClass('current');		
	   
			});
	
		})(jQuery);
	}

	if("HYPE_eventListeners" in window === false) {
		window.HYPE_eventListeners = Array();
	}
	window.HYPE_eventListeners.push({"type":"HypeDocumentLoad", "callback":myCallback});

 </script>

That’s a bit of a stab in the dark though; I’d need to see a zip of your .hype document to advise better.