Reputation: 11759
I'm looking for a best practice on how to disable a link that would redirect to the same page with jquery/ jquerymobile.
For example if I'm on the hompepage and there's a link pointing to homepage, it should not even refresh the page.
Code of my link:
<a href="Homepage.aspx" rel="external">Home</a>
Upvotes: 0
Views: 932
Reputation: 36043
for (var a = document.getElementsByTagName("A"), b = 0; b < a.length; b++) {
if (a[b].href === window.location.href.split("#")[0] && a[b].hasChildNodes()) {
for (var c = 0; b < a[b].childNodes.length; c++) {
a[b].parentNode.insertBefore(a[b].childNodes[c].cloneNode(!0), a[b]);
}
}
}
Upvotes: 0
Reputation: 3534
You could parse the current URL with window.location.href
and extract the page name.
Then, you can iterate on each link and append behaviour for link that have the same href value as the current page value
var currentPage = ....// extract the page from window.location.href
$('a').each(function(index, element) {
var currentA = $(this);
if (currentA.attr('href') == currentPage) {
// Append a listener on the click event that will return false
// and stop the default behaviour
currentA.on('click', false);
}
});
Note: setting false as the handler function is the same as creating a anonymous function that return false, and is again the same as creating a function that call event.stopPropoagation()
and event.preventDefault()
Upvotes: 1
Reputation: 3818
I'm not familiar enough with jquery/jquery mobile to know if this is a best practice, but it should work.
$("a").each(function(){
if(window.location.href==this.href)
this.onclick=function(){return false};
});
Upvotes: 1
Reputation: 892
Totally untested, but depending on how your code is written this could work.
$('a').each(function(){
if($(this).attr('href') === window.location.pathname)
$(this).removeAttr('href');
// Alternatively: $(this).attr('href','#');
});
Upvotes: 1