Why is javascri[t working in preview but not on the front end?

I have added this code to hide an element when an option is selected it works in the back end when I am in custumizer but not when on the front end. Do I need to change the format of the code or have I done something wrong?

jQuery('table.variations select').on('change', function() {

value = $(this).val(); //take value from options


  if (value != '') { //if value is not choose than hide
$('.vanish').css('display', 'None'); //hiding div
  }else{
 $('.vanish').css('display', ''); //show div again 
  }

});

Hello @wicara,

Thanks for writing in!

Please have your code updated and use this instead:

(function($){
	$('table.variations select').on('change', function() {
	    value = $(this).val();
	    if (value != '') {
	        $('.vanish').css('display', 'None');
	    } else {
	        $('.vanish').css('display', '');
	    }
	});	
})(jQuery);

Hope this helps.

1 Like

so have to wrap any code or just in that format should i rewrite it another way instead ?

Hey @wicara,

You do not have to wrap it with any tag or code. Just insert the updated code.

Please let us know how it goes.

That worked thank you, will I have to wrap any script with $ with the (function($){ })(jQuery);

?

Hello @wicara,

Yes, you will have to insert the correct jQuery code so that it will work when applied to the page.

(function($){
	$('.selector').on('change', function() {
              /* things to do */
	});	
})(jQuery);

By inserting the correct code, you can always make sure that it is independent and will not create conflicts or issues later on.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.