Pages

Tuesday, 27 August 2013

Hyperlinks not working with jQuery mobile... Why?


Mobile jQuery processes each and every link and considers it as an ajax by default which will loads in the same page and not refresh the entire page. Links that point to other domains or that have rel="external", data-ajax="false" or target attributes will not be loaded with Ajax. Instead, these links will cause a full page refresh with no animated transition. Both attributes (rel="external" and data-ajax="false") have the same effect, but a different semantic meaning: rel="external" should be used when linking to another site or domain and data-ajax="false" is useful for simply opting a page within your own domain from being loaded via Ajax. Because of the security restrictions, the framework always opts links to external domains out of the Ajax behavior.

Let’s have a look at an example. I have many links on the page already and let’s say we have to popup using mobile jQuery. Adding rel="external" to each link is not possible as there are around thousand of links on my page. So using jQuery we can use the following code:

$(document).ready(function(){
    $("a").each(function(){
          $(this).attr("rel","external");
    });
}); 

The above code will apply rel attribute to all the links on the page. But if we want to 
implement a simple popup using the following code:
 
 <a href="#popupBasic" data-rel="popup">Open Popup</a>
 <div data-role="popup" id="popupBasic">
      <p>This is a completely basic popup, no options set.</p>
</div>
 
we will get issues as the “rel” attribute will also be applied to the link for popups too. 
So we can add a condition as shown below to avoid adding rel attribute to popup links:
 
$(document).ready(function(){
    $("a").each(function(){
        if($(this).attr("data-rel")!="popup") {
            $(this).attr("rel","external");
        }
    });
});

For more information click here
 
                                           

2 comments: