Replace main image with the clicked one - javascript

There's a main image, and right underneath it there are 10 smaller ones. When you click on the small picture number 6 for example, the main picture gets replaced by the picture 6, and the heading above it changes from 'Pic1.jpg' to 'Pic6.jpg'. What would be the most efficient way to do this with js?
Here's what I tried:
function changeImage() {
var m = document.getElementById("mainimgid");
m.src = document.getElementById(this.id).src;
}
And in HTML:
<img src="img/Pic2.jpg" class="imgmini" id="2" onclick="changeImage()"></img>

Use onClick event to pass the clicked img info and then change the main element with what you want. Here is my aproach with cute cats:
function changeImage(img) {
document.getElementById("mainimgid").src=img.src;
document.getElementById("text").innerText = img.alt
}
img {
width:100px;
}
<div>
<p id="text">Cute cat</p>
<img src="https://i.pinimg.com/originals/c8/27/78/c827782e12851cd2cf4c5161c4f5445a.jpg" class="imgmini" id="mainimgid" onclick="changeImage(this.src)"></img>
</div>
<div>
<img src="https://i.pinimg.com/originals/fc/ca/a0/fccaa0fb45fae275fa1b2dd147f1f189.jpg" class="imgmini" id="2" onclick="changeImage(this)" alt="Cute cat1"></img>
<img src="https://filmdaily.co/wp-content/uploads/2020/04/cute-cat-videos-lede-1300x882.jpg" class="imgmini" id="1" onclick="changeImage(this)" alt="Cute cat2"></img>
</div>

Try doing this
function changeImage(newMainImage) {
var m = document.getElementById("mainimgid");
m.src = newMainImage.src;
}
var newImage = document.getElementById("newImageID");
newImage.onclick = () => changeImage(newImage)

Make the link to pass the event object,
<img src="img/Pic2.jpg" class="imgmini" id="2" onclick="changeImage(event)"></img>
2.Change the event listener to recieve the passed event object
function changeImage(event) {
....
}
Now you can know which link has triggered the event
function changeImage(event) {
let clickedImage = event.target;
let clickedImageSrc = clickedImage.getAttribute("src");
let m = document.getElementById("mainimgid");
m.setAttribute("src",clickedImageSrc);
}

Related

How get src value when click on one of the mulitple images in javascript?

I have 3 images in my web page. I want to get src value every time when I clicked on any image. I tried following code but its not working with multiple images.
<div class="test">
</div>
</div>
</div>
</div>
<script type="text/javascript">
function filename(){
//var fullPath = document.getElementsByClassName('dImage').src;
var fullpath = document.getElementsByClassName('dImg').src
console.log(fullPath);
var filename = fullPath.replace(/^.*[\\\/]/, '');
var fileid = filename.split("\deckel.")[0];
//window.location.href = "web-rocketcreator.html?="+fileid;
console.log(fileid);
}
</script>
As the other answers have mentioned the specific problem area, here's an alternative solution.
Instead of attaching a click event to each image you can attach one to the container and listen for events as they bubble up the DOM (known as event delegation.)
// Grab the container, and add an event listener to it
const imageContainer = document.querySelector('.test');
imageContainer.addEventListener('click', filename, false);
function filename(event) {
// Pick out the src attribute from target element
// (the image that was clicked on)
const { target: { src } } = event;
// Use the src as the basis for the rest of
// your calculations
var filename = src.replace(/^.*[\\\/]/, '');
var fileid = filename.split("\deckel.")[0];
console.log(`web-rocketcreator.html?=${fileid}`);
}
.test a {
display: block;
}
<div class="test">
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-1.png" alt="">
</a>
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-2.png" alt="">
</a>
<a href="#" class="part-one">
<img class="dImage" src="images/deckel-3.png" alt="">
</a>
</div>
To get a reference to the object which triggered the click event you need to pass the keyword this as a parameter.
In your case this object is the <a> element. To get it's nested children - the <img> element you need to call the .children method which returns an array. Since there's just the image element you can directly reference it using children[0] and ultimately add the .src property to retrieve the source.
function filename(element){
console.log(element.children[0].src);
}
<div class="test">
</div>
Get src value from image when clicking on it
When you call a function from onClick() you can pass 'this' to the function. This way you will directly have a reference to the clicked element inside the functon
<img src="xxxx.jpg" onclick="myFunction(this)" />
function myFunction(element) {
const src = element.src;
}
Get src value from image when clicking on parent container
<a onclick="myFunction(this)"><img src="xxxx.jpg" /></a>
function myFunction(link) {
const src = link.children[0].src
}

JQuery click attr('src') return Undefined

The images loads from ko.observableArray
<ul data-bind="foreach: images">
<li>
<div class="photo">
<h2></h2>
<img data-bind="attr:{src: '/images/'+path}, click: $root.addImageUrl">
</div>
</li>
After click on the image i want to get image src and add it to another ko.observableArray
I have following script
self.addImageUrl = function () {
var src = $("img",this).attr('src');
self.selectedImages.push(src);
};
But returns Undefined.
You are wrong to use this. In addImageUrl function this is not element. I can suggest you to use img object instead (itัั‹ not explicitly passed to function):
self.addImageUrl = function (img) {
var src = '/images/' + img.path;
self.selectedImages.push(src);
};
Demo
The selector $("img",this).attr('src'); is wrong.
Use $(this).attr('src'); to get the src of the clicked image.

ListView item animations - Windows store app

I create simple grid application using basic grid example in visual studio and this tutorial. I expected this animation will work on all item's, but it seems that it works only on first one. My question is, how can I animate this on all item's? And if it is possible to animate randomly(not all at once! Example: windows 8 start menu).
Item template:
<div class="itemtemplate" data-win-control="WinJS.Binding.Template">
<div class="item">
<img class="item-image" src="#" data-win-bind="src: backgroundImage; alt: title" />
<img class="item-image-new" src="#" data-win-bind="src: backgroundImage; alt: title" />
<div class="item-overlay">
<h4 class="item-title" data-win-bind="textContent: title"></h4>
<h6 class="item-subtitle win-type-ellipsis" data-win-bind="textContent: subtitle"></h6>
</div>
</div>
</div>
Js animation:
var darkGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY3B0cPoPAANMAcOba1BlAAAAAElFTkSuQmCC";
var lightGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY7h4+cp/AAhpA3h+ANDKAAAAAElFTkSuQmCC";
var mediumGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY5g8dcZ/AAY/AsAlWFQ+AAAAAElFTkSuQmCC";
// Play the Peek animation
function peekTile(tile1, tile2) {
// Create peek animation
var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
// Reposition tiles to their desired post-animation position
tile1.style.top = "-250px";
tile2.style.top = "0px";
// Execute animation
peekAnimation.execute();
}
function changeImage() {
// Get the two image elements
var images = document.querySelector(".item-image");
var imagesNew = document.querySelector(".item-image-new");
// Swap out the old image source and choose the new image source
images.src = imagesNew.src;
if (images.src == lightGray)
imagesNew.src = mediumGray;
else if (images.src == mediumGray)
imagesNew.src = darkGray;
else
imagesNew.src = lightGray;
// Reset the elements for the pre-animation position and trigger the animation
images.style.top = "0px";
imagesNew.style.top = "250px";
peekTile(images, imagesNew);
};
And interval, that changes images(it is written inside ready function):
setInterval(function () { changeImage() }, 4000);
When you call document.querySelector it will only return the first matching element, which in your case will be the first list item. If you want to animate any random item, just call document.querySelectorAll(".item"), pick a random item from the result list and then call querySelector('.item-image') on it, proceeding as you currently do.

find the img id and src and adding to the array

Heres my html code:
<div id="cmdt_1_29d" class="dt_state2" onclick="sel_test(this.id)">
<img id="cmdt_1_29i" onclick="dropit('cmdt_1_29');"
src="http://hitechpackaging.zes.zeald.com/interchange-5/en_US/ico_minus.png">
<span class="dt_link">
CARTON & BOARD
</span>
</div>
<div id="cmdt_2_31d" class="dt_istate1" onclick="sel_test(this.id)">
<img src="/site/hitechpackaging/images/items/test.jpb ">
CORRUGATED & CORNER BOARD
</div>
The dropit function modifies my img src which I dont want to, unfortunately I cant modify,
Can I somehow read the data into array before it is being modified and that I can add the data back to the image.
To remove the click handler:
var i = document.getElementById('cmd1_1_29i');
i.onclick = null;
Or, if you want to still call the original click handler:
var i = document.getElementById('cmd1_1_29i');
_onclick = i.onclick;
i.onclick = function(e) {
// do what you want here
_onclick && _onclick.apply(this, [e]);
}
โ€‹

Background-Image fade jquery

I have a div and I want to fade in and out of 5 different background images at random.
I have downloaded a jquery plugin for this, but unfortunately it alternates - I'll explain.
You must set a default background image (for this case lets say "image1") and then load an array of images (say image2, image3, image4, and image5). What the plugin does is duplicate the div and place it directly over the original one, then fades in and then out one of the array of images. The undesirable effect that I'm getting from this is:
1,2,1,3,1,4,1,5
as opposed to:
1,2,3,4,5
Because the fade out simple reveals the default image once again.
Without re-inventing the wheel is there a way to modify the code to that when the fade-in animation is complete (the default is completely concealed) I swap out the image on the background div so that when the fade out begins there's a new image below? I'm relatively new to JQuery and so this is not my strength.
Heres the action part of the plugin:
var tempImage = new Image();
jQuery(tempImage).load( function(){
var newImage = ( helperElement.css('display') == 'block' ) ? jQuery(this) : jQuery(helperElement);
newImage.css('backgroundImage', 'url('+tempImage.src+')');
helperElement.animate( settings.effect, settings.duration, settings.easing, settings.callback );
});
tempImage.src = src;
And in my HTML:
<script>
document.getElementById('content_container_home').style.backgroundImage = "url('img/buttons.jpg')";
$( function(){
var bgImages = [ 'barker.jpg', 'boards.jpg', 'feet.jpg', 'glasses.jpg' ];
var currImage = 'buttons.jpg';
setInterval( function(){
do{
var randImage = bgImages[Math.ceil(Math.random()*(bgImages.length-1))];
}while( randImage == currImage )
currImage = randImage;
$('#content_container_home').BgImageTransition( 'img/'+currImage );
}, 5000)
});
</script>
Check out my answer to another question
This should do the trick:
HTML:
<div id="testers">
<div class="tester">
<img src="http://regmedia.co.uk/2008/03/18/google_adwords_machine.png" alt="" />
</div>
</div>
<div id="morework">
<div class="holderdiv">
<div class="tester">
<img src="http://www.swwebs.co.uk/images/google-pagerank.jpg" alt="" />
</div>
</div>
<div class="holderdiv">
<div class="tester">
<img src="http://jsfiddle.net/favicon.gif" alt="" />
</div>
</div>
</div>
CSS:
#morework{display:none;}
jQuery:
$(document).ready(function(){
function runIt(){
$('#morework').find('.holderdiv').each(function(i, elem) {
$("#testers").delay(5000).fadeOut(1000, function() {
$(this).html($(elem).html());
}).fadeIn(1000, runIt);
});
};
runIt()
});
Check it out in action here - http://jsfiddle.net/sfsPx/

Categories