How to disconnect communication with javascript and css?

Do you know how to disable a user-only link? I have

<div class="searchoffertext" onclick="searchoffertext_selected('Banana')"><a href="./search/Banana">Banana</a></div> 

So the idea is that link / search / Banana is a valid link, and I want to keep it for search index engines. However, I want when the user clicks on the link, the searchoffertext_selected function is called and nothing else happens.

+6
source share
4 answers

To stop the link from the default action, add return false; in the onclick event:

 <div class="searchoffertext" onclick="searchoffertext_selected('Banana'); return false;"><a href="./search/Banana">Banana</a></div> 

It is probably best to place onclick directly on <a>

But it would be even better to use unobtrusive JavaScript to attach an event to a link through a selector.

See also: fooobar.com/questions/952526 / ...

+9
source

Using jQuery:

 $('#selector').click(function(e){ e.preventDefault(); }); 

VanilaJS:

 <a onclick="return false;"> 
+3
source

Try it?

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> 
+1
source

HTML

 <div class="searchoffertext" onclick="searchoffertext_selected('Banana')"> <a href="./search/Banana">Banana</a> </div> 

CSS

Use pointer-events , but this is not supported in versions of IE older than 11 years .

 .searchoffertext > a { pointer-events: none; } 

Javascript

Prohibit the default action when clicking a link:

 var links = document.querySelectorAll('.searchoffertext > a'), i; for(i = 0; i < links.length; i += 1) { links[i].addEventListener('click', function(e) { e.preventDefault(); }, false); } 
-2
source

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


All Articles