0

I have a menu placed on website's header. One of the menu links looks like that:

<a href="#" class="controlpanel-link">&nbsp;Control Panel</a>

I have a jQuery function that should make visible a popup:

$(document).ready(function(){
    jQuery(".controlpanel-link").click(function() {
        $("#controlpanel").show();
    });
    jQuery("#close-cp").click(function() {
        $("#controlpanel").hide();
    });
});

As it is in the header, it appears on all pages. On the index page the jQuery is executed, on other pages nothing is happening and the console is not showing any errors. What should I do in this case?
Thank you in advance!

Grigore Dodon
  • 137
  • 3
  • 13

1 Answers1

0

Before we start, I'd clean this code up a little bit. This ensure's that the jQuery object you're interacting with in your code doesn't affect other javascript and vice-versa. It's also shorthand in jQuery for $(document).ready For more insight, see reference on closures below.

(function($){
  $(".controlpanel-link").click(function() {
    $("#controlpanel").show();
  });
  $("#close-cp").click(function() {
    $("#controlpanel").hide();
  });
})(jQuery);

There are a few things that may be contributing to this behavior:

  1. If this is a single page web app, it is possible that the elements you bind click to are not bound when a new view is rendered.
  2. Depending on what other javascript you may have, the elements may not exist on the page.

Debugging

If you haven't already, I suggest at least using your javascript console and console.log statements to see if your click events are actually being triggered. The console will also inform you of any javascript errors your code may be producing. If you're up to it, I'd suggest using breakpoints for more advanced debugging.

References

Javascript closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

jQuery $(document).ready: https://learn.jquery.com/using-jquery-core/document-ready/

console.log: https://developer.mozilla.org/en-US/docs/Web/API/Console/log

"Set a javascript breakpoint in code - in chrome": Set a javascript breakpoint in code - in chrome?

Community
  • 1
  • 1
pygeek
  • 7,356
  • 1
  • 20
  • 41