How can I add a link around every image on a page? - javascript

I want to add a link to all images on the page. The link should point to the image source.
For example, from this:
<img src="foo.jpg">
I want to get this:
<img src="foo.jpg">
I tried to do it like the following but nothing seems to happen. Do I then have to somehow add the new "a" element somewhere?
var images = document.getElementsByTagName('img');
for (var image in images) {
var a = document.createElement('a');
a.href = image.src;
a.innerHtml = image;
}

You are iterating over the indices (0, 1, 2, ...) of images in this line:
for (var image in images) {
If image were an HTML element, this line still wouldn't work because the innerHTML property expects HTML text, not an object:
a.innerHtml = image;
Finally, you have neglected to add the anchor to the document.
Here is a correct way to do it:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; ++i) {
var img = images[i];
var a = document.createElement('a'); // Make a new anchor.
a.href = img.src; // Point it at the image source.
img.parentNode.replaceChild(a, img); // Replace the image with the anchor.
a.appendChild(img); // Make the image a child of the anchor.
}
<img src="http://i.stack.imgur.com/bcOyt.png">
<img src="http://i.stack.imgur.com/IPkNZ.png">
<img src="http://i.stack.imgur.com/Kd7GM.png">

You just create the Tag, but not insert it to the Document.
You can use replaceChild method in Node to replace the Img tag.

May I suggest jQuery?
The following example won't work in the sandbox because of browser restrictions, but should work on a site that you control. Also, depending on circumstances, the browser might block the popup. But, in the case of links within the webpage own domain, this might be the better solution, because you avoid manipulating the DOM.
$(function () {
$('img').on('click', function () {
var win = window.open($(this).attr('src'), '_blank')
win.focus()
})
})
img {
border: 1px solid blue;
cursor: pointer;
float: left;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
Here is another approach, wrapping all the images in an a tag as you originally requested:
$(function () {
$('img').wrap(function () {
return ''
})
})
img {
border: 1px solid blue;
cursor: pointer;
float: left;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">

for each loops are somewhat strange in javascript, you need to access objects like this:
for (var image in images) {
var a = document.createElement('a');
a.href = images[image].src;
a.innerHtml = images[image];
a.appendChild(images[image]);
// then of course you need to replace the img with the anchor containing the image
images[image].parentNode.replaceChild(a, images[image]);
}
Generally speaking:
for(var obj in list) {
var current = list[obj];
}

Related

Clicking image should display the respective image in another div using JavaScript only

HTML
<div class="user">
<img id="select" class="rock" src="images/rock-removebg-preview.png" onclick="addImg()">
<img id="select" class="paper" src="images/paper-removebg-preview.png" >
<img id="select" class="scissors" src="images/scissors-removebg-preview.png" >
</div>
<div class="player-box"></div>
Javascript
function addImg() {
rock.removeAttribute('onclick')
const newElement = document.createElement('img');
newElement.src = 'images/rock-removebg-preview.png'
playerBox.appendChild(newElement);
rock.addEventListener('onclick', addImg)
}
I am trying trying to create a function where when the image is clicked that respective image gets displayed in the player-box div. I tried a few different variation of javascript programs and none of them are working the way I want it to. Any help would be appreciated.
Details are commented in example below
// Reference the <form>
const RPS = document.forms.RPS
// Register the click event to <form>
RPS.onclick = addIMG;
// Pass the Event Object
function addIMG(e) {
// Reference all form controls
const IO = this.elements;
// The tag that the user cklicked
const clk = e.target;
// Clean #player to make room.
IO.player.replaceChildren();
/*
** Match clicked tag #id to <img>
*/
if (clk.matches('.rps')) {
switch (clk.id) {
case 'rock':
IO.player.insertAdjacentHTML('afterbegin', `<img src='https://www.biography.com/.image/ar_16:9%2Cc_fill%2Ccs_srgb%2Cg_faces:center%2Cq_auto:good%2Cw_1920/MTc5NjIyODM0ODM2ODc0Mzc3/dwayne-the-rock-johnson-gettyimages-1061959920.webp' height='150'>`);
break;
case 'paper':
IO.player.insertAdjacentHTML(
'afterbegin',
`<img src='https://d1csarkz8obe9u.cloudfront.net/posterpreviews/notebook-paper-background-design-template-c114c2ed2104bd8b815cf7fbb2f34f44_screen.jpg?ts=1636989881' height='150'>`);
break;
case 'scissors':
IO.player.insertAdjacentHTML(
'afterbegin',
`<img src='https://smithsverdict.files.wordpress.com/2013/02/johnny-depp-as-edward-scissorhands-1990.jpeg' height='150'>`);
break;
default:
break;
}
}
}
#objects {
display: flex;
justify-content: space-evenly;
}
object {
display: block;
margin: 0 15px;
cursor: pointer;
}
#player {
width: auto;
max-height: 150px;
text-align: center;
}
img {
object-fit: contain;
}
<form id="RPS">
<fieldset id='objects'>
<legend>Pick One</legend>
<object id="rock" class="rps">🪨</object>
<object id="paper" class="rps">🧻</object>
<object id="scissors" class="rps">✂</object>
</fieldset>
<fieldset id="player">
<legend>Player</legend>
</fieldset>
<fieldset id='opponent'>
<legend>Opponent</legend>
</fieldset>
</form>
Only create the new image once, if it hasn't been created already. On click, copy the src attribute of the clicked image to the one created inside the playerbox div.
See how it works by running the snippet and clicking one of the three images...
// this "lazy" getter for playerImg will either return or create the img
function playerImg() {
let playerImg = document.getElementById('playerimg');
if (!playerImg) {
playerImg = document.createElement('img');
playerImg.id = 'playerimg';
document.getElementById('playerbox').appendChild(playerImg);
}
return playerImg;
}
// set the source attribute of the playerImg
function setPlayerImg(src) {
playerImg().setAttribute('src', src);
}
// get the rock, paper, scissors elements with their common class
const imgs = document.getElementsByClassName("myclass");
// for each, add a click handler that calls our src setting function
for (let i = 0; i < imgs.length; i++) {
const el = imgs[i];
el.addEventListener('click', () => setPlayerImg(el.src), false);
}
<div class="user">
<img class="rock myclass" src="https://dummyimage.com/100x100/0f0/000" />
<img class="paper myclass" src="https://dummyimage.com/100x100/ff0/000" />
<img class="scissors myclass" src="https://dummyimage.com/100x100/0ff/000" />
</div>
<div id="playerbox"></div>
HTML elements with an id are directly put into javascript variables.
It's not the case with classes (since multiple html elements can have the same class name).
So if you'd use
<div id="user">
<img id="select" id="rock" src="images/rock-removebg-preview.png" onclick="addImg()">
<img id="select" id="paper" src="images/paper-removebg-preview.png" >
<img id="select" id="scissors" src="images/scissors-removebg-preview.png" >
</div>
<div id="player-box"></div>
Your code should work.
Else, if you need to use class names, use const rock = document.querySelector('.rock') and const playerBox = document.querySelector('.player-box').
Also, i'm not sure why you're removing the onclick attribute just to add the same listener again.
Also, when adding the event listener, the name of the event is 'click' and not 'onclick'.

I am trying to replace an image with the other one by using javascript but it isn't working.I am new to javascript [duplicate]

I want to change an image to some other image when i click on the object. the code is stacked in the following order:
<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>
What I wish to do is, when I click on the <li> i want to change the image to a coloured version of the image, i.e. some other image. Now, I know I can use JQuery/JS to accomplish it. But I don't want a huge amount of JS code to accomplish something so simple.
Can it be done using something simpler? Like pseudo selectors? .active class?
I cannot seem to think of it.
To change image onclik with javascript you need to have image with id:
<p>
<img alt="" src="http://www.userinterfaceicons.com/80x80/minimize.png"
style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()"/>
</p>
Then you could call the javascript function when the image is clicked:
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "http://www.userinterfaceicons.com/80x80/minimize.png"){
document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/maximize.png";
} else {
document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/minimize.png";
}
}
This code will set the image to maximize.png if the current img.src is set to minimize.png and vice versa.
For more details visit:
Change image onclick with javascript link
Or maybe
and that is prob it
<img src="path" onclick="this.src='path'">
How about this? It doesn't require so much coding.
$(".plus").click(function(){
$(this).toggleClass("minus") ;
})
.plus{
background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_blue.png");
width:130px;
height:130px;
background-repeat:no-repeat;
}
.plus.minus{
background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_minus.png");
width:130px;
height:130px;
background-repeat:no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="plus">CHANGE</div>
If your images are named you can reference them through the DOM and change the source.
document["imgName"].src="../newImgSrc.jpg";
or
document.getElementById("imgName").src="../newImgSrc.jpg";
The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you'll need to use some JS.
I would name the images starting with bw_ and clr_ and just use JS to swap between them.
example:
$("#images").find('img').bind("click", function() {
var src = $(this).attr("src"),
state = (src.indexOf("bw_") === 0) ? 'bw' : 'clr';
(state === 'bw') ? src = src.replace('bw_','clr_') : src = src.replace('clr_','bw_');
$(this).attr("src", src);
});
link to fiddle: http://jsfiddle.net/felcom/J2ucD/
Here, when clicking next or previous, the src attribute of an img tag is changed to the next or previous value in an array.
<div id="imageGallery">
<img id="image" src="http://adamyost.com/images/wasatch_thumb.gif" />
<div id="previous">Previous</div>
<div id="next">Next</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$( document ).ready(function() {
var images = [
"http://placehold.it/350x150",
"http://placehold.it/150x150",
"http://placehold.it/50x150"
];
var imageIndex = 0;
$("#previous").on("click", function(){
imageIndex = (imageIndex + images.length -1) % (images.length);
$("#image").attr('src', images[imageIndex]);
});
$("#next").on("click", function(){
imageIndex = (imageIndex+1) % (images.length);
$("#image").attr('src', images[imageIndex]);
});
$("#image").attr(images[0]);
});
</script>
I was able to implement this by modifying this answer: jQuery array with next and previous buttons to scroll through entries
If you don't want use js, I think, you can use instead of img and then use css like
a {
background: url('oldImage.png');
}
a:visited {
background: url('newImage.png');
}
EDIT: Nope. Sorry it works only for :hover
You can try something like this:
CSS
div {
width:200px;
height:200px;
background: url(img1.png) center center no-repeat;
}
.visited {
background: url(img2.png) center center no-repeat;
}
HTML
<div href="#" onclick="this.className='visited'">
<p>Content</p>
</div>
Fiddle
This script helps to change the image on click the text:
<script>
$(document).ready(function(){
$('li').click(function(){
var imgpath = $(this).attr('dir');
$('#image').html('<img src='+imgpath+'>');
});
$('.btn').click(function(){
$('#thumbs').fadeIn(500);
$('#image').animate({marginTop:'10px'},200);
$(this).hide();
$('#hide').fadeIn('slow');
});
$('#hide').click(function(){
$('#thumbs').fadeOut(500,function (){
$('#image').animate({marginTop:'50px'},200);
});
$(this).hide();
$('#show').fadeIn('slow');
});
});
</script>
<div class="sandiv">
<h1 style="text-align:center;">The Human Body Parts :</h1>
<div id="thumbs">
<div class="sanl">
<ul>
<li dir="5.png">Human-body-organ-diag-1</li>
<li dir="4.png">Human-body-organ-diag-2</li>
<li dir="3.png">Human-body-organ-diag-3</li>
<li dir="2.png">Human-body-organ-diag-4</li>
<li dir="1.png">Human-body-organ-diag-5</li>
</ul>
</div>
</div>
<div class="man">
<div id="image">
<img src="2.png" width="348" height="375"></div>
</div>
<div id="thumbs">
<div class="sanr" >
<ul>
<li dir="5.png">Human-body-organ-diag-6</li>
<li dir="4.png">Human-body-organ-diag-7</li>
<li dir="3.png">Human-body-organ-diag-8</li>
<li dir="2.png">Human-body-organ-diag-9</li>
<li dir="1.png">Human-body-organ-diag-10</li>
</ul>
</div>
</div>
<h2><a style="color:#333;" href="http://www.sanwebcorner.com/">sanwebcorner.com</a></h2>
</div>
function chkicon(num,allsize) {
var flagicon = document.getElementById("flagicon"+num).value;
if(flagicon=="plus"){
//alert("P== "+flagicon);
for (var i = 0; i < allsize; i++) {
if(document.getElementById("flagicon"+i).value !=""){
document.getElementById("flagicon"+i).value = "plus";
document.images["pic"+i].src = "../images/plus.gif";
}
}
document.images["pic"+num].src = "../images/minus.gif";
document.getElementById("flagicon"+num).value = "minus";
}else if(flagicon=="minus"){
//alert("M== "+flagicon);
document.images["pic"+num].src = "../images/plus.gif";
document.getElementById("flagicon"+num).value = "plus";
}else{
for (var i = 0; i < allsize; i++) {
if(document.getElementById("flagicon"+i).value !=""){
document.getElementById("flagicon"+i).value = "plus";
document.images["pic"+i].src = "../images/plus.gif";
}
}
}
}

How to add image into the specific section of the achor tag in javascript?

I have three images and two anchor tags. When user click on any link then user can select any image.Then this image must be replaced with anchor tag image in which user clicked.
var control3 = document.getElementById('control1').src;
var control4 = document.getElementById('control2').src;
function getImage(e) {
fullpath = e.children[0].src;
var filename = fullpath.replace(/^.*[\\\/]/, '');
var imageSrc = filename.split("\.")[0] + ".png";
if (control1 !== fullpath) {
document.getElementById('control1').src = "images/" + imageSrc;
}
if (control2 !== fullpath) {
document.getElementById('control2').src = "images/" + imageSrc;
}
if (control3 !== fullpath) {
document.getElementById('control3').src = "images/" + imageSrc;
}
}
<img onclick="getImage(this);" src="images/image1.png" alt="">
<img onclick="getImage(this);" src="images/image2.png" alt="">
<img onclick="getImage(this);" src="images/image3.png" alt="">
<img id="control1" src="">
<img id="control2" src="">
You've really only implemented part of the process here. You need to consider the flow of the program more carefully:
You need firstly to handle click events on the links.
And you also need to make it possible for users to click on an image to select it for replacement.
Then your code needs to be able to match the clicked image to the clicked link, so it knows what change to make.
N.B. in this demo I've replaced your inline event handlers with unobtrusive event handlers using addEventListener (i.e. declared in the JS, not embedded in the HTML).
//variables to hold program state
var selectEnabled = false;
var selectedImage = "";
//handle clicks on links
var links = document.querySelectorAll(".imageLink");
links.forEach(function(lnk) {
lnk.addEventListener("click", enableImageSelection);
});
function enableImageSelection(e) {
e.preventDefault(); //stop the hyperlink doing its normal job (i.e. moving to another page)
selectEnabled = true;
alert("Please select an image to replace");
imageSrc = this.querySelector("img").src;
}
//handle clicks on the replaceable images
var clickableImages = document.querySelectorAll(".clickableImage");
clickableImages.forEach(function(img) {
img.addEventListener("click", loadImage);
});
function loadImage() {
if (selectEnabled == true) {
console.log("replacing " + this.src + " with " + imageSrc);
this.src = imageSrc;
selectEnabled = false; //image is not clickable again until a link is clicked first.
}
}
<img class="clickableImage" src="images/image1.png" alt="1" />
<img class="clickableImage" src="images/image2.png" alt="2" />
<img class="clickableImage" src="images/image3.png" alt="3" />
<br/><br/>
<img src="images/image4.png"> Click me
<img src="images/image5.png"> Click me
I don't fully understand what you want from your explanation but I guess it's something like this:
Have lots of images and two empty "boxes".
Click on a box and you can click on an image.
The box will update when you clicked on the image.
optional: make it dynamic, so you can add any amount of images or "boxes".
In order to do so you need to:
Know what box you first clicked on.
Tell the images you can select between that they can be clicked.
Update the original box with the clicked image.
bonus: give the user feedback (highlights).
var selectedImageId = ""; // 1. Know what box you first clicked on.
const SELECTABLE_CLASS_NAME = 'selectable';
// 1. Know what box you first clicked on.
function selectImage(imageElement) {
let selectableImagesContanier = document.getElementById('selectables');
if (selectedImageId && selectedImageId != imageElement.id) {
let prevSelectedImage = document.getElementById(selectedImageId);
prevSelectedImage.classList.remove(SELECTABLE_CLASS_NAME);
}
selectedImageId = imageElement.id;
// 4. bonus: give the user feedback (highlights)
imageElement.classList.add(SELECTABLE_CLASS_NAME);
selectableImagesContanier.classList.add(SELECTABLE_CLASS_NAME);}
function getImage(imageElement) {
let selectableImagesContanier = document.getElementById('selectables');
// 2. Tell the images you can select between that they can be clicked.
if (selectableImagesContanier.classList.contains(SELECTABLE_CLASS_NAME)) {
let imageToBeUpdated = document.getElementById(selectedImageId);
// 3. Update the box with the clicked image.
imageToBeUpdated.src = imageElement.src;
// 4. bonus: give the user feedback (highlights)
selectableImagesContanier.classList.remove(SELECTABLE_CLASS_NAME);
imageToBeUpdated.classList.remove(SELECTABLE_CLASS_NAME);
imageToBeUpdated.classList.add('image-shown');
}
}
img {
width: 50px;
height: 50px;
border: 2px solid;
border-color: transparent;
}
#selectables.selectable > img,
img.selectable {
border-color: lightblue;
cursor: pointer;
}
.selected-image-container {
margin-top: 1rem;
}
.selected-image-container > img {
cursor: pointer;
background-color: lightgrey;
}
.selected-image-container > img.image-shown {
background-color: transparent;
}
<div id="selectables">
<img onclick="getImage(this)" src="https://picsum.photos/id/21/50/50" alt="">
<img onclick="getImage(this)" src="https://picsum.photos/id/31/50/50" alt="">
<img onclick="getImage(this)" src="https://picsum.photos/id/41/50/50" alt="">
</div>
<div class="selected-image-container">
<img id="control1" src="" onclick="selectImage(this)">
<img id="control2" src="" onclick="selectImage(this)">
</div>

adding current class to automated image changer

I have a kind of a image rotator that scrolls through an array of images via javascript within a certain interval, and now I have added some style to each current image. But that only works if I myself hover over the items/click on the items, whenever the script swaps images on auto, nothing happens stylistically to the images.
So what I want to know is how I can use the same effect on the auto script.
Here is the code
*HTML *
<div class="container-thumbs">
<div><a><img src=".jpg" /></a></div>
<div><a class="active"><img src=".jpg" /></a></div>
<div><a><img src=".jpg" /></a></div>
</div>
CSS
.container-thumbs{
width: 300px; height: 25; font-size: 18px;
}
.container-thumbs a{
list-style: none; float: left; margin-right: 4px; padding: 5px;
}
.container-thumbs div a:hover, .container-thumbs div a.active {
background-color: #f90;
}
Javascript
(function(){
var rotator = document.getElementById('bigImage');
var imageDir = '../images/headers/';
var delayInSeconds = 5;
var images = ['.jpg', '.jpg', '.jpg', '.jpg', '.jpg',
'.jpg', '.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
bigImage.src = imageDir + images[num++];
if (num == len)
{num = 0;}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
i think u have to replace bigImage with rotator
because the u getTheImage
var rotator = document.getElementById('bigImage');
// then u dont use it
bigImage.src = imageDir + images[num++];
// so try to change to
rotator.src=imageDir + images[num++];
goodluck
From your html there is no element with an ID of bigImage, so I cannot see how this works at all.
I have added the ID in the middle image as below:
<div class="container-thumbs">
<div><a><img src=".jpg" /></a></div>
<div><a class="active"><img src=".jpg" id="bigImage" /></a></div>
<div><a><img src=".jpg" /></a></div>
</div>
That should work.
One other thing, is there a good reason not to use jQuery here? I'd strongly recommend it for cross-browser compatibility if nothing else.

On-Click img border = #color - Multiple images - Only need 1 highlighted at a time

Basically what I am trying to accomplish is create a list of images (let's say 10) and upon clicking any of these images, their border changes to a specific color; currently accomplishing this with a simple onClick event with JS. That's not an issue. The trouble comes in when clicking a second or third or forth image; all of the images clicked remain highlighted, of course. I would like to set it so that only the last (current) image selected in the set remain with the border color changed.
What is the best way to accomplish this simple effect?
Below is a simple working example:
<!doctype html>
<html>
<head>
<title>Website.com</title>
<style type="text/css">
.normal {
border:none;
}
.highlighted {
border:1px solid #336699;
}
</style>
<script type="text/javascript">
var ImageSelector = function() {
var imgs = null;
var selImg = null;
return {
addImages: function(container) {
imgs = container.getElementsByTagName("img");
for(var i = 0, len = imgs.length; i < len; i++) {
var img = imgs[i];
img.className = "normal";
img.onclick = function() {
if(selImg) {
selImg.className = "normal";
}
this.className = "highlighted";
selImg = this;
};
}
}
};
}();
</script>
</head>
<body>
<div>
<div id="menu">
<img src="cube.png" width="30" height="30" />
<img src="cube.png" width="30" height="30" />
<img src="cube.png" width="30" height="30" />
<img src="cube.png" width="30" height="30" />
<img src="cube.png" width="30" height="30" />
<img src="cube.png" width="30" height="30" />
<img src="cube.png" width="30" height="30" />
</div>
</div>
<script type="text/javascript">
var div = document.getElementById("menu");
ImageSelector.addImages(div);
</script>
</body>
</html>
This does not use any library such as jQuery. Its just plain 'ol js. Also the code is for the sake of example
I would take advantage of jQuery. Give each of your images a class, for example, "imageHighlight" or something. Then you could do something like this (completely untested):
$(document).ready(function() {
$('img.imageHighlight').click(function() {
$('img.imageHighlight').css('border-width', 0);
$(this).css('border-width', '3px');
});
});
And have some CSS with it:
img.imageHighlight {
border: 0px solid #345678;
}
There's probably even a better way to do it by toggling CSS classes or something, but I'm lazy at the moment. Still digesting lunch :)

Categories

Resources