How to redirect from DIV and bypass child href anchor

Please, I need your help with the code below. I want to add an onclick event for the whole DIV to redirect to the url, but I cannot get around the href included in the child anchor inside the DIV .:

i.e. (The goal is to redirect a click to google.com anywhere in the image or text):

<html> <div onclick="location.href='http://www.google.com'"> <div> <a href="http://en.wikipedia.org/"> <img height="200" width="200" src="http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"> </a> Test </div> </div> </html> 

This works fine when I use a local url like "file: /// E: /Documents/Blog/Design/Tmp1.html" (I don't know why). Thanks.

Update: I add the idea of ​​this query: I need this for the Index section of my blog, which Blogger builds with the same program as for individual posts. In the index, I want every click in the main Div to be redirected to the message, but inside the message, clicking on the image should go to the href image. My idea was that the onclick event was added dynamically in the DIV for the Index section only.

+4
source share
3 answers

If you intend to do this inline (not recommended, but this is your code), you can add return false; to the inner anchor:

 <html> <div onclick="location.href='http://www.google.com'"> <div> <a href="http://en.wikipedia.org/" onclick="return false;"> <img height="200" width="200" src="http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"> </a> Test </div> </div> </html> 

Update: based on step 2 of your request (this is a terrible, scary idea for a number of reasons, but it works):

 <html> <div onclick="location.href='http://www.google.com'"> <div> <a href="http://en.wikipedia.org/" onclick="if ( this.parentElement.parentElement.onclick ) { return false; }" id="demo"> <img height="200" width="200" src="http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"> </a> Test </div> </div> </html> 
+3
source

Install the onclick handler using javascript. the code will look something like this:

 document.getElementById("mydiv").onclick = function(){ // navigate to new page window.location.href = 'URL'; } 

You will need to add id to your div and pass it correctly in the getElementById function.

0
source

You can also try something like this:

 <div onClick="window.open('http://www.google.com','_blank');"> 

Change _blank with _self if you want it to open in the same window.

0
source

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


All Articles