When I use this code inside my HTML document it\'s working:
$(\'a.tocenter[href*=#]\').click( function() {
if (location.pathname.replace(/^\\//,\'\') ==
You're attaching an event handler to an element using .click()
, so it needs to be there at this point.
This can be guaranteed if you check for the page ready
:
$(function() {
// your code
});
or window load
:
$(window).load(function() {
// your code
});
, or if you keep the script in the page, at its end:
Another way is to use delegation
:
$(selector_for_element_that_will_surely_be_there).on(event, selector_for_element_receiving_the_event, function() {
// your code
});
// ie:
$(document).on('click', 'a.tocenter[href*=#]', function() {
// your code
});
Have a look about it: http://api.jquery.com/on/