0

Is there any specific way for click event handlers for hash-change pages? For example, suppose I have a page ​abc.com​. Clicking on a specific tab gives us abc.com#/tab1, a hashed page. On the hashed page, I want to add click event on, say, Save​ button.

My implementation assumes that the elements are all child nodes of body and hence using event-delegation. However, the same does not work as desired.

window.addEventListener("hashchange", function () {
    console.log(window.location.hash);
    $( "body" ).on( "click", "button", function( event ) {
      if (window.location.hash === "#/tab1")
        console.log("testing success");
    });
});
  • Hey, congrats on asking your first Stackoverflow question :) welcome! I made a few edits. Most were trivial spacing edits to the text, but I also changed your code block to be formatted by leading with 4 spaces. The back-tick is generally used when you want to have a bit of code inline like `this for example` – jaydel Jul 31 '16 at 16:10

1 Answers1

0

As mentioned in the answer of this post, you can use jQuery approach for this one:

$(window).on('hashchange', function() {

  console.log(window.location.hash);

    saveButton = $('#saveBtn:not(.bound)');
    if (saveButton != undefined) {
        saveButton.addClass('bound').click(function(){
            if (window.location.hash == '#/tab1') {
                console.log('testing success!');
            }
        });
    }
});

Checking for .bound class ensures that the click event is bound only once to the saveButton. (Source here)

Community
  • 1
  • 1
Julius Delfino
  • 991
  • 10
  • 27
  • Thanks for the response. Its partially working. The issue is, initially when I click on the _Save_ button its not working. However, when I revisit the page again, its working. My current implementation uses .ready() to check if the DOM contents are loaded or not, but still its not working. The code is provided in the next comment. – Wridhee Bhattacharya Aug 01 '16 at 13:16
  • `$(document).ready(function() { button = $("div.class button"); console.log(button); console.log($("div.class button").length); if (button !== undefined) { $("div.class button").click(function() { if (window.location.hash == '#/tab-1') { console.log('testing success new 2!'); } }); } }); ` – Wridhee Bhattacharya Aug 01 '16 at 13:16
  • `div.class button` refers to a – Julius Delfino Aug 01 '16 at 17:21
  • Instead of "div.class button", can you try using just "button", or specifically, the id of your _Save_ button? – Julius Delfino Aug 01 '16 at 17:24