Skip to content Skip to sidebar Skip to footer

Change Image In Element Onclick

I have an a href element with an image - and another links with an image. I want to swap the target image with the image from the clicked link. Target:
Copy

Documentation: http://api.jquery.com/attr/

Solution 2:

First, let's give the target an ID for easier usage in vanilla JS:

<div class="mainPicture">
    <imgid="targetImg"src="/img/0~7183AF0F-799A-4248-A9B0-848F038DE194~400~300~1"class="photo"alt="MC812-REF"></div>

You could then use:

<li><arel="colorboxRel1930551650"href="/img/0~C19CB486-F38E-4F27-999F-200B35EFB916~640~480~1"class="testColorbox cboxElement"onclick="document.getElementById('targetImg').src = this.childNodes[0].src; return false;"><imgsrc="/img/0~C19CB486-F38E-4F27-999F-200B35EFB916~70~70~1"alt="Närbild"title="Närbild"></a></li><li><arel="colorboxRel1930551650"href="/img/0~E1E5892F-0A22-4DA0-A9F8-3A93C4461125~640~480~1"class="testColorbox cboxElement"onclick="document.getElementById('targetImg').src = this.childNodes[0].src; return false;"><imgsrc="/img/0~E1E5892F-0A22-4DA0-A9F8-3A93C4461125~70~70~1"alt="Höger vinkel"title="Höger vinkel"></a></li>

...However I'm not sure how your href and rel attributes are supposed to work there.

For a jQuery solution, it would probably be best to leave to onclick alone and use this JavaScript code:

$(function() {
    $("a.testColorbox.cboxElement").click(function() {
        $(".mainPicture img").attr("src", $("img", this).attr("src"));
    });
});

Solution 3:

$("a").on("click", function() {
  $(this).siblings("img").first().attr("src", this.getAttribute("href"));
});

Pure JS

document.addEventListener("DOMContentLoaded", function() {
  var links = document.getElementsByTagName("a");

  for (var i = 0; i < links.length; i++) {
    links[i].addEventListener("click", function(e) {
      e.preventDefault();

      this.firstElementChild.setAttribute("src", this.getAttribute("href"));
    });
  }
});

Post a Comment for "Change Image In Element Onclick"