DOM click() event and link fragments in

If you have <a href=”#anchor”> style links click() event does not perform as expected on the link element.

Think the following jQuery Mobile code on <a href=”#ancho”>:

$list.delegate( "li", "click", function(event) {
 if ( !$( event.target ).closest( "a" ).length ) {
   var a = $( this ).find( "a" );
   a.first().trigger( "click" );
   return false;
  }
})

This code would go to  directory/#anchor instead of directory/page.html#anchor.

This does seem to be desired behavior as both Firefox and Webkit engines do it. However, it is quite puzzling.

Here is a temporary workaround directly hacked into jQuery Mobile version:

// tapping the whole LI triggers click on the first link
 $list.delegate( "li", "click", function(event) {
  if ( !$( event.target ).closest( "a" ).length ) {
 
  var a = $( this ).find( "a" );                
  var href = a.attr("href");
 
  if(href && href[0] == '#') {
     window.location.hash = href;    
     return true;
   } else {
     a.first().trigger( "click" );    
   }                
   return false;
   }
 });

This case surfaced when debugging why jQuery Mobile list views didn’t work correctly on Sphinx table of contents internal to the page.

Also, onhashchange listener in jQuery Mobile has to be disabled, but it seems to be irrelevant for this case.

Leave a Reply

Your email address will not be published. Required fields are marked *