Maximus
Maximus

Reputation: 19

jQuery to make images clickable (wrap them in a href)

Is there a way to make each image (that has a certain class) clickable?

I want jQuery to:

  1. Read the src of the image.
  2. Wrap the image with an a href that contains that src url.

.clickable {
padding: 20px;
border: 1px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<img src="https://www.google.com/logos/doodles/2020/stay-and-play-at-home-with-popular-past-google-doodles-fischinger-2017-6753651837108768-s.png" class="clickable">

Upvotes: 0

Views: 178

Answers (5)

matthias_h
matthias_h

Reputation: 11416

You can do it like this:

$("img.clickable").wrap("<a href='" + $('img').attr('src') + "'></a>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://www.google.com/logos/doodles/2020/stay-and-play-at-home-with-popular-past-google-doodles-fischinger-2017-6753651837108768-s.png" class="clickable">

Upvotes: 1

Saurav Sen Sarma
Saurav Sen Sarma

Reputation: 29

can you brief the scenario, not getting your point?

got your point: - you can use the following to wrap all the images having class clickable with and and with href as the image src

$('.clickable').each(function(){
    src = $this.attr('src');
    $this.wrap("<a href='" + src  + "'></a>");
})

Upvotes: 0

anees
anees

Reputation: 1855

$(document).ready(function(){
$("img.clickable").each(function(i){
  $(this).wrap(`<a href="${($(this).attr('src'))}"></a>`)
 })
})
.clickable {
padding: 20px;
border: 1px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<img src="https://www.google.com/logos/doodles/2020/stay-and-play-at-home-with-popular-past-google-doodles-fischinger-2017-6753651837108768-s.png" class="clickable">

Upvotes: 1

Itay Daniel Zecharia
Itay Daniel Zecharia

Reputation: 21

try this:

var url=$(".clickable").attr("src");
$("a").attr("href", url);

Upvotes: 0

Rithik Banerjee
Rithik Banerjee

Reputation: 467

I hope you want something like this:

$('.clickable').on('click', function() {....})

let me know if I am wrong.

Upvotes: 0

Related Questions