Reputation: 717
I have the following markup which I can't change.
<a href="link-to-somepage.html"><img src="link-to-image.jpg"></a>
Is there any way for me to make these images unclickable? i have tried setting pointer-events
to none
on img
but that does not work. Setting them to none
on all a
tags will make every link unclickable.
Is there some way for me to make only the links around images unclickable? I would prefer a CSS based solution, if one exists. :)
Upvotes: 0
Views: 149
Reputation: 87292
You could do like this, where you float
the image in combination with pointer-events: none
As the image is floated its parent will collapse to size 0 because of a BFC is established, and the anchor won't grow with its content unless you create a BFC on it.
a > img {
float:left;
pointer-events: none
}
<a href="#" onclick="alert('click');"><img src="http://placehold.it/100x100"></a>
If you gonna use this with flowed text, like below, you'll need to wrap it in a span
.
a > img {
float:left;
pointer-events: none
}
span {
display: inline-block; /* needed if its gonna be flowed with text */
}
Hey, here is a link with an image <span>
<a href="#" onclick="alert('click');"><img src="http://placehold.it/100x30"></a>
</span>, one which can't be clicked on
Upvotes: 3
Reputation: 51
There is no way to select a parent based on it's child in CSS at present. Since you cannot change your markup, JavaScript seems to be the only way.
You want to select all the anchor tags whose immediate child is an image. In order to accomplish this,
Below is a pure JavaScript solution:
var imgs = document.querySelectorAll("a > img");
var a;
for(var i=0; i < imgs.length; i++){
a = imgs[i].parentNode;
a.href = "#";
}
Upvotes: 1
Reputation: 68685
If you can't change the markup so try to use jQuery. Get all images and after that all a
tags which are the immediate parent of the images
. And by using click
event handler preventDefault().
$('img').parent('a').on('click', function(e){
e.preventDefault();
return false;
})
or as was said by @t.niese in the comments you can also use
$(document).on('click', 'a:has(>img)' function(e){
e.preventDefault();
return false;
});
For more you can see example
$('img').parent('a').on('click', function(e){
e.preventDefault();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='www.google.com'>Google1</a>
<br/>
<a href='google.com'><img src='https://www.google.ru/images/branding/googleg/1x/googleg_standard_color_128dp.png' alt='an image'>Google 2</a>
Upvotes: 4
Reputation: 410
You can do it by CSS class also just use that class on anchor tag which you don't want to get clicked like
.no-click{
pointer-events : none !important;
}
<a class="no-click" href="link-to-somepage.html"><img src="link-to-image.jpg"></a>
Upvotes: 2