S
S
simpleasthat2016-04-10 11:12:02
JavaScript
simpleasthat, 2016-04-10 11:12:02

Why might a JS function not work?

Hello.

There is a site that has .fa-bars and #menu-main-nav elements with the following styles:

i.fa-bars {
display: none;
}
#menu-main-nav {
display:block;
}
@media (max-width: 768px) {
#menu-main-nav {
display: none;
}
i.fa-bars {
display: inline-block;
}
}


I am trying to execute the following script:
jQuery(document).on('click touchstart', '.fa-bars', function() {
jQuery("#menu-main-nav").prependTo(document.body)
jQuery("#menu-main-nav").show();
});

, however, does not work at all from what is inside the function. There are no errors in the browser console.

I tried to reproduce the same in jsfiddle, everything works, link .
Tried using click(), same result.

jQuery is included, other scripts run without problems. If you run the code from the browser console, it will execute successfully. Tell me, please, in which direction to dig, I'll never know why the script in this case may not work. Thank you! jQuery("#menu-main-nav").prependTo(document.body)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2016-04-10
@simpleasthat

although you write that there are no errors in the console, try this:
1 wrap your code in something like this
(function($){
"use strict";
$(document).ready(function(){
// your code here
});
// or your code here
// you can use '$' here and not ' jQuery'
}(jQuery));
2 check if you are loading your code before including jquery.
and if at the time of executing the #menu-main-nav
3 code, see if you have some other event hanging on .fa-bars that fires first

D
Dima Pautov, 2016-04-10
@bootd

Well, for starters, you can write it shorter))

$(document).on('click touchstart', '#trigger', function() {
      $("#a").appendTo(document.body).show();
  });

And then, it's hard to say why it doesn't work for you, but here everything is ok. Give a link to your site. This will make it easier to understand

A
Alexander, 2016-04-10
@lasmaster

A small comment to the code. If you notice that you have duplicate selectors in your code, move them to separate variables and then work with them. This will make the code easier to maintain, and accessing a variable is faster than accessing a selector.
PS Dima Turkov is right, use chain method calls, it also simplifies the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question