Do you know how to disable link for user only? I have
<div class="searchoffertext" onclick="searchoffertext_selected('Banana')"><a href="./search/Banana">Banana</a></div>
So idea is that link /search/Banana is a valid link and I want to keep it for search indexing engines. However, I want when user click on link, the function searchoffertext_selected was called and nothing more happened.
-
You want user to see the redirected page or not? if not, why you need to keep it in an anchor tag. Use buttons instead?AKIWEB– AKIWEB2013年08月26日 18:27:49 +00:00Commented Aug 26, 2013 at 18:27
-
Just for search engines. I do not know how they work with ajax data.Tigran– Tigran2013年08月26日 21:19:39 +00:00Commented Aug 26, 2013 at 21:19
4 Answers 4
To stop the link from taking its default action add return false; to the onclick event:
<div class="searchoffertext" onclick="searchoffertext_selected('Banana'); return false;"><a href="./search/Banana">Banana</a></div>
It's probably a better idea to put the onclick directly on the <a>
But an even better approach would be to use unobtrusive JavaScript to attach an event to the link via a selector.
Comments
Using jQuery:
$('#selector').click(function(e){
e.preventDefault();
});
VanilaJS:
<a onclick="return false;">
4 Comments
return false !== preventDefault() Try this?
js
document.querySelectorAll('.searchoffertext > a').onclick = function(e) {
e.preventDefault();
searchoffertext_selected(this.getAttribute("data-fruit"));
}
html
<div class="searchoffertext">
<a href="./search/Banana" data-fruit="Banana">Banana</a>
</div>
6 Comments
click event of a div..searchoffertext > a, so there are no div events here> a in there before.[0] missing after the selector, i.e. ...querySelectorAll('.searchoffertext > a')[0].onclick... because, unlike with the almighty jQuery, stuff doesn't automatically apply to the entire list of elements.HTML
<div class="searchoffertext" onclick="searchoffertext_selected('Banana')">
<a href="./search/Banana">Banana</a>
</div>
CSS
Use pointer-events, but this is unsupported in versions of IE older than 11.
.searchoffertext > a {
pointer-events: none;
}
JavaScript
Prevent the default action from executing when the link is clicked:
var links = document.querySelectorAll('.searchoffertext > a'), i;
for(i = 0; i < links.length; i += 1) {
links[i].addEventListener('click', function(e) {
e.preventDefault();
}, false);
}