Ad

How To Make An Image A Link When Screen Becomes Small

- 1 answer

I'm building a web page to learn about responsive web development and have run into a problem with my links. When the page width is small I would like to add hyperlinks to my images however when it becomes large I would like to take them off the images and put them on another element. Is there a way to do this with HTML, CSS and/or JavaScript?

For more context please take a look at this slideshow where I have added a breakpoint at screen width 450px. When the screen is wider, the hyperlink is on the "Read More" button, however I would like it to be on the image when the "Read More" button disappears.

Ad

Answer

If you wanted to use jQuery, you could do something like this:

Demo

JS:

$(document).ready(function() {
  moveLink();
});

$(window).resize(function() {
  moveLink();
});

function moveLink() {  
  if ($(window).width() >= 450) {
    $("#myImage").unwrap();
    $("#myText").wrap('<a target="_blank" rel="nofollow noreferrer" href="https://www.stackoverflow.com">').show();
  } else {
    $("#myText").unwrap().hide();
    $("#myImage").wrap('<a id="myLink" target="_blank" rel="nofollow noreferrer" href="https://www.stackoverflow.com"></a>');
  }
}

HTML:

<img id="myImage" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150">
<br>

  <span id="myText">Read More</span>
Ad
source: stackoverflow.com
Ad