Capturing hashchange events not related to click bindings

I am trying to use Javascript to emulate the CSS :target pseudo- :target to catch all the events that result in such an element on the page. I defined three trigger events:

  • window.location.hash already targeting an element with the same identifier during initialization
  • Snap to snap element
  • The hashchange event is hashchange regardless of the above (for example, through the window.history API)

Scenario 2 is important as a separate case, since I would like to trigger the click preventDefault event. The following is simplified code for this scenario:

 $('body').on('click', 'a[href*=#]', function filterTarget(clickEvent){ $(this.hash).trigger('target', [clickEvent]); }); 

The problem occurs when trying to implement scenario 3:

 $(window).on('hashchange', function filterTarget(hashChangeEvent){ $(this.hash).trigger('target', [hashChangeEvent]); }); 

If the target handler does not cancel the native behavior for script 2, it will be run again when the native behavior raises the resulting hashchange event. How can I filter out these edge cases?

CHANGE POST SOLUTIONS:

the fried response held the key - it processed the hashchange event with names, then untied and rewrote the handler based on the logic processed inside the click handler and its prevention Default. I wrote a complete plugin here .

+4
source share
3 answers

If I understand this, you do not want the hashchange event to fire if you click on the anchor tag. Then you can set your logic using events with names:

Demo

 $('body').on('click', 'a[href*=#]', function (clickEvent) { filterTarget(clickEvent,this); $(window).off('hashchange.filter').on('hashchange.tmp', function () { $(this).off('hashchange.tmp').on('hashchange.filter', filterTarget); }); }); $(window).on('hashchange.filter', filterTarget); function filterTarget(event,elem) { $(elem?elem.hash:window.location.hash).trigger('target', [event]); //you could filter depending event.type alert(event.type + '::'+ (elem?elem.hash:window.location.hash)); } 
+5
source

if the click sets the hash with the fragment anyway, just throw away duplicates in the hash change event:

 onhashchange=function(e){ if(e.newURL == e.oldURL ){return; } //do your normal hashchange event stuff below: }; 

ref: https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange

this fixes cascading issues no matter what caused the change.

+1
source

It looks like you could use mousedown instead of clicking if you are going to call preventDefault on it. Then, presumably, the hash exchange will not work.

0
source

Source: https://habr.com/ru/post/1489525/


All Articles