Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link not working on image?

I've been attempting to create an effect where a user clicks on an image, that image is replaced by another image which also acts as a link.

However my problem is that whenever I click the replaced image, the link doesn't work.

Fiddle: http://jsfiddle.net/ha6qp7w4/321/

$('.btnClick').on('click',function(){
    $(this).attr('src','https://placekitten.com/g/200/300')
    $(this).attr('href','google.com')
});
like image 645
KingAlfredChameleon Avatar asked Nov 22 '22 22:11

KingAlfredChameleon


1 Answers

img tags don't have href properties. You need to wrap the image in an anchor and assign the url to that, or do a custom redirect.

Notice your image html on inspection of element:

<img src="https://placekitten.com/g/200/300" id="1" class="btnClick" href="google.com"> <!-- not valid! -->

This isn't valid because imgs aren't anchors!

function first() {
    this.src = 'https://placekitten.com/g/200/300';
    $(this).unbind("click");
    $(this).on("click", second);
}

function second() {
    window.location.href = "https://www.google.com";
    $(this).unbind("click");
    $(this).on("click", first);
}

$('.btnClick').on('click', first);

(I tried to make a fiddle but it wouldn't save, but this should work)

You need to store your actions in functions so you can revert if need be. First action is the change the source, then change the event to redirect you like a link.

like image 102
Sterling Archer Avatar answered Nov 24 '22 12:11

Sterling Archer