Replace the main image with thumbnails in Javascript - javascript

Here my script :
function changeImage(event){
event = event || window.event;
var targetElement = event.target || event.srcElement;
if (targetElement.tagName == "IMG"){
document.getElementByClass("img-big-wrap").src = targetElement.getAttribute("src");
document.getElementById("mainimageLink").href = 'link'+targetElement.getAttribute("data-link")+'.html';
}
}
Inspired of this Answer : Javascript Gallery - Main Image href change
My HTML :
<div class="gallery-wrap">
<div class="img-big-wrap">
<a id="mainimagelink" href="<?php echo $data[0][gallery][0][photo];?>">
<img class="img-big-wrap" src="<?php echo $data[0][gallery][0][photo];?>" alt="">
</div>
<div class="img-small-wrap" onclick="changeImage(event)">
<div class="item-gallery"> <img src="<?php echo $data[0][gallery][1][thumb];?>" data-link="1"> </div>
<div class="item-gallery"> <img src="<?php echo $data[0][gallery][2][thumb];?>" data-link="2"> </div>
<div class="item-gallery"> <img src="<?php echo $data[0][gallery][3][thumb];?>" data-link="3"> </div>
<div class="item-gallery"> <img src="<?php echo $data[0][gallery][4][thumb];?>" data-link="4"> </div>
</div>
</div>
The code is actualy just open me the link of the main image only
I want to change the main image with the thumbnails when I click On, I dont know if what i'm doing is the good solution

Working Plunk: http://plnkr.co/edit/pjpHBUD4yPihqr7lJKAD?p=preview
<div class="gallery-wrap">
<div>
<a id="mainimagelink" href="https://blog.conservation.org/wp-content/uploads/2014/06/ci_19290600_cropped.jpg">
<img class="img-big-wrap" src="https://blog.conservation.org/wp-content/uploads/2014/06/ci_19290600_cropped.jpg?>" alt="">
</a>
<hr/>
</div>
<div class="img-small-wrap" ">
<div class="item-gallery " onclick="changeImage(event) "> <img src="https://s5.favim.com/610/52/Favim.com-winter-nature-small-canon-eos-7d-474348.jpg " data-link="1 "> </div>
<div class="item-gallery " onclick="changeImage(event) "> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTfAMUZQLGObfUBSLgnPj5b5C7Ww2DNMtKbwkuTbglK-p1La17BnA " data-link="2 "> </div>
</div>
</div>
A couple of things you've missed.
The HTML DOM was not well constructed. The tag with id mainimagelink was left unclosed, leading to opening of the main image everytime you clicked on any image.
Not sure of your use case but I believe you were trying to create a thumbnail gallery with a preview. Added Image URLs and CSS to simulate the API response.
'img-big-wrap' class was used for the image container and the actual Image itself, which would lead to errors when you try to locate your element with js.
document.getElementByClass is not the right name for the method. I believe you were going for 'document.getElementsByClassName' which returns an array as multiple elements can have the same className.
Refer to querySelector (most useful of them all):
https://www.w3schools.com/jsref/met_document_queryselector.asp
All the best!

First of all, you have used the same class more than once and tried to access it img-big-wrap.
There is also no accessor called getElementByClass instead use
getElementsByClassName which is an array since you can have multiple divs with the same class.
Typo here "mainimageLink" which you called your div with id="mainimagelink", case matters.
I have moved onclick into JS using addEventListener which saves me passing parameters from the div.
Add an id into your thumbnail parent div myImgDiv and used it to hook an Event Listener to it.
Here is what the code looks like (Not many changes were made):
let smallImgDiv = document.getElementById('myImgDiv');
smallImgDiv.addEventListener('click', (e) => {
let targetElement = e.target || e.srcElement;
let tagName = targetElement.tagName;
if(tagName === "IMG") {
document.getElementById('bigImage').src = targetElement.getAttribute("src");
document.getElementById("mainimagelink").href = 'link' + targetElement.getAttribute("data-link") + '.html';
}
});
.img-small-wrap img{
width: 150px;
height: 150px;
}
.img-big-wrap {
height: 200px;
}
<div class="gallery-wrap">
<div class="img-big-wrap">
<a id="mainimagelink" href="#">
<img id="bigImage" class="img-big-wrap" src="http://via.placeholder.com/300.png" alt="">
</a>
</div>
<div id="myImgDiv" class="img-small-wrap">
<div class="item-gallery"> <img src="https://getuikit.com/v2/docs/images/placeholder_200x100.svg" data-link="1"> </div>
<div class="item-gallery"> <img src="https://cdn.dribbble.com/users/312581/screenshots/1676038/female-placeholder_1x.png" data-link="2"> </div>
<div class="item-gallery"> <img src="https://d30y9cdsu7xlg0.cloudfront.net/png/1134418-200.png" data-link="3"> </div>
<div class="item-gallery"> <img src="https://source.sierrawireless.com/~/media/developer%20zone/icons/sw_dz_icons_placeholder.ashx?h=240&la=en&w=240" data-link="4"> </div>
</div>

Related

Javascript/Jquery - Get the link of a visible image

I have some modals where there are some images. I also have a download button, that should download just the shown (the only visible) image in the modal.
I tried to make that the href link of the download button is equal to the visible image href, but it it doesn't seem to work...
Here you can see the full page code, but the part that interests me is this one:
<div id="myModal_12" class="modal">
<div class="modal-content">
<div class="Slide mySlides_12">
<div class="numbertext">1 / 3</div>
<img src="uploads/IMG_4946.JPG43879.jpg" class="little_image" style="width:50%;">
</div>
<div class="Slide mySlides_12">
<div class="numbertext">2 / 3</div>
<img src="uploads/IMG_4949.JPG21730.jpg" class="little_image" style="width:50%;">
</div>
<div class="Slide mySlides_12">
<div class="numbertext">3 / 3</div>
<img src="uploads/IMG_4950.JPG72501.jpg" class="little_image" style="width:50%;">
</div>
<!-- Next/previous controls -->
<div class="input-group-btn">
<a onclick="downloadFunction(this)">Download this image</a>
</div>
<span class="close cursor" onclick="closeModal(12)">
<img src="/images/close.png">
</span>
<a class="prev" style=" display: block; " onclick="plusSlides(-1, 12)">❮</a>
<a class="next" style=" display: block; " onclick="plusSlides(1, 12)">❯</a>
</div>
</div>
</div>
<script>
function downloadFunction(linkElement) {
var little_image = document.getElementsByClassName("little_image"); // Get all the images with that class
var right_image = $(little_image).not(":hidden"); // Get just the visible image
var src = right_image.src;
linkElement.href = src; // Set the link href on the visible image src
}
</script>
The JavaScript function return an "undefined" value...
Any help is very appreciated
To get the src attribute of an element you should use the attr(<attribute>) method. Given what you are trying to do, this logic could be reduced to:
linkElement.href = $('.little_image:visible').attr('src');
As Taplar has said you can use:
linkElement.href = $(".little_image:visible").attr("src");
However, there is an issue. The jQuery function returns an array and if you added another element that fits this criteria before this element that could cause an issue. Since attr returns for the first element of that array it may not work for the proper element you wanted it to. To fix this you could write this:
linkElement.href = $(".little_image:visible")[1].getAttribute("src"); // [1] the second element
If you want to get an attribute of element you should use attr function. In your problem you need to call like this;
linkElement.href = right_image.attr('src');
In addition, if you want to set an attribute then use .attr(attribute, value) like this:
right_image.attr("src", "https://www.example.com/")

Mouseover function not working for first time

With this function i want to replace a static image with an animated image (gif) on mouseover. But it's not working only on FIRST mouseover. Is there someone that could help me?
JQuery function:
function mouseListener(imageDiv, image, animated, static)
{
$(function() {
$(imageDiv).hover(
function() {
$(image).attr("src", animated);
},
function() {
$(image).attr("src", static);
}
);
});
}
HTML:
<div onmouseover="mouseListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" id="would_youDiv" class="container">
<a href="work.html">
<img id="would_you" class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
You could make this much easier by generalizing the logic with classes and data elements.
$(document).ready(function() {
$('.hover-image-container').hover(
function() {
//find the image in the container
var $img = $(this).find('img');
//set the src to the animaged src on it
$img.attr('src', $img.data('animated-src'));
},
function() {
//find the image in the container
var $img = $(this).find('img');
//set the src to the original src
$img.attr('src', $img.data('src'));
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container hover-image-container">
<a href="work.html">
<img src="images/would_you.jpg" data-src="images/would_you.jpg" data-animated-src="images/would_you.gif" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
Your mouseListener method is called when the mouseover event occurs, which is when it creates the listener to the event, instead of acting on the event. You don't need to add the listener, since you've already registered the function to be called on mouse over, you just need to do the action you want for that event.
You need to either put that binding somewhere else, or create two methods that are bound to onmouseover and onmouseout.
For example, if you want to go the two methods route (as that's most similar to your current code):
<div onmouseover="mouseOverListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" onmouseout="mouseOutListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" id="would_youDiv" class="container">
<a href="work.html">
<img id="would_you" class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
And then in your Javascript:
function mouseOverListener(imageDiv, image, animated, static) {
$(image).attr("src", animated);
}
function mouseOutListener(imageDiv, image, animated, static) {
$(image).attr("src", static);
}
You don't need a js function
HTML
<div class="container">
<a href="work.html">
<img class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" onmouseover="this.src='images/would_you.gif'" onmouseout="this.src='images/would_you.jpg'"/>
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>

DOM traversing using jQuery

I am trying to create a comparison overlay that shows items selected by users when they 'add to compare' link.(like one in flipkart that appears on top when you hit add to compare). Here is my code:
<div class="college-list-container">
<div class = "individual-college-container" id="text1">
<div class="image-header"><h3>text1</h3>
</div>
<div class="dark-overlay">
<div class="overlay-links" style=" float:left;"> <div class="absolute-center ">Details</div></div>
<a href=""> <div class="overlay-links" style=" float:right; border-right:none;"> <div class="absolute-center comparison" id="comparison">Add to compare</div>
</div></a>
</div>
</div>
<div class = "individual-college-container">
<div class="image-header"><h3>text2</h3>
</div>
<div class="dark-overlay">
<div class="overlay-links" style=" float:left;"> <div class="absolute-center ">Details</div></div>
<a href=""> <div class="overlay-links" style=" float:right; border-right:none;"> <div class="absolute-center comparison">Add to compare</div>
</div></a>
</div>
</div>
<div class = "individual-college-container" id="itm">
<div class="image-header" ><h3>text3</h3>
</div>
<div class="dark-overlay">
<div class="overlay-links" style=" float:left;"> <div class="absolute-center ">Details</div></div>
<a href=""> <div class="overlay-links" style=" float:right; border-right:none;"> <div class="absolute-center comparison">Add to compare</div>
</div></a>
</div>
Javascript
/show overlay when one checkbox is checked and add its name/image to the empty space
$('.comparison').click(function(e){
var clgId = $(this).parentsUntil('.individual-clg-container').find('.image-header').text();
e.preventDefault();
var clg = $("<li></li>")
clg.text(clgId);
var removeLink = $("<a href=''>(Remove)</a>");
clg.append(removeLink)
$('.comparison-colleges').append(clg);
$('.add-to-compare-overlay').show("slide", { direction: "up" }, 300);
});
I want the text in the div containing class 'image-header' to be assigned to the variable clgId. The problem that i am facing with my code is that it is adding the text of all the divs containing class 'image-header'. Ex i want the value text1 to be assigned on clicking add to compare of the div with id text1. However it assigns 'text1 text2 text3' to clgId.
Please help
I've created a JSFiddle with what I think is your desired functionality (I included a console log output in the script of the clgId variable):
http://jsfiddle.net/py38kuvv/
I replaced the parentsUntil function with the closest function (and replaced the individual-clg-container class selector):
var clgId = $(e.target).closest('.individual-college-container').find('.image-header').text();
and also updated your click handler:
$('.comparison').on( "click", function(e) {
In order to get a quicker response in future, posting a JSFiddle of what you have so far makes it easier for others to help :)
It is adding all of them because
var clgId = $(this).parentsUntil('.individual-clg-container').find('.image-header').text();
should be
var clgId = $(this).parentsUntil('.individual-college-container').find('.image-header').text();

jquery: how to append DOM element to selector within variable containing other DOM elements

When storing DOM elements in a javascript variable prior to appending them to the actual DOM is there a way with jQuery to select elements inside the variable?
For example,
I have a list of tweets on my page. Every time I click a refresh button I append a new tweet to the list below.
I add the new tweet like follows:
new tweet
<li class="tweet normal-tweet" data-user-name="Dorothy">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=Dorothy" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/Dorothy" title="Dorothy">Dorothy</a>
<div class="full-name"></div>
</div>
<div class="text">Once in a lullaby</div>
<div class="time-stamp" data-time="1322631934000">1322631934000</div>
</div>
</li>
Inside each tweet on the page, not the new tweet yet, I use jQuery to append some elements.
I have:
var actionsMarkup =
"<div class='actions'>
<span class='favorite'>Favorite</span>
<span class='retweet'>Retweet</span>
<span class='reply'>Reply</span>
</div>";
and I append it to the element with the .content class
$(actionsMarkup).appendTo('#tweets .tweet .content');
Now, when I make a new tweet I do the following:
$(document).on('click', '.refresh', function() {
newTweet = $(<new tweet code from above>);
actionsMark = $(actionsMarkup);
$(newTweet.appendTo('#tweets');
I need to be able to append the actionsMark contents to the div with class .content. However, I can't just reapply my prior statement of
$(actionsMarkup).appendTo('#tweets .tweet .content');
because that puts the markup on all .content divs again, even if it is already there.
Is there a way for me to use selectors to access the DOM nodes in my newTweet variable before I append it to the document object?
I am thinking something like
$(actionsMarkup).appendTo( newTweet, '.content');
If there is no way with selectors to do this then what are some other quick ways?
List of Tweets and Tweet container
<ul id="tweets" class="normal-tweet show-promoted-tweets">
<li class="tweet promoted-tweet" data-user-name="Dorothy">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=Dorothy" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/Dorothy" title="Dorothy">Dorothy</a>
<div class="full-name">Dorothy</div>
</div>
<div class="text">Somewhere over the rainbow</div>
<div class="time-stamp" data-time="1322631934000">3 minutes ago</div>
</div>
</li>
<li class="tweet promoted-tweet" data-user-name="lion">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=lion" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/lion" title="lion">lion</a>
<div class="full-name">Lion</div>
</div>
<div class="text">Way up high,</div>
<div class="time-stamp" data-time="1322631934000">17 minutes ago</div>
</div>
</li>
<li class="tweet normal-tweet" data-user-name="scarecrow">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=scarecrow" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/scarecrow" title="scarecrow">scarecrow</a>
<div class="full-name">Scarecrow</div>
</div>
<div class="text">And the dreams that you dreamed of,</div>
<div class="time-stamp" data-time="1322631934000">32 minutes ago</div>
</div>
</li>
</ul>
You can use .last(), to select the last element after you append your new tweet, like below:
$(document).on('click', '.refresh', function() {
newTweet = $(<new tweet code from above>);
$(newTweet).appendTo('#tweets');
var actionsMarkup =
"<div class='actions'>
<span class='favorite'>Favorite</span>
<span class='retweet'>Retweet</span>
<span class='reply'>Reply</span>
</div>";
$("#tweets .tweet").last().find(".content").append(actionsMarkup);
});
if you insist to use appendTo(), you can try using :last-child:
$(actionsMarkup).appendTo('#tweets .tweet:last-child .content');
I was looking to see if you can do the same thing, found this question but the existing answer is not useful in my case as i would like to alter the element before adding.
You can create a new dom element in a variable with jQuery and do operations on it as if it is already in the dom before appending it.
Example:
var newTweet = $('<div></div>');
newTweet.addClass('tweet');
newTweet.append('<span class="username"></span>');
newTweet.find('span.username').html('John Doe');
$('body').append(newTweet);
the following will be appended to the body:
<div class="tweet"><span class="username">John Doe</span></div>
Very handy if you are building a reusable interface element (like a dialogue box) with multiple options.

How to get each element and assign them an inline style contained inside the child

I've been looking for an elegant solution for a day now and I am pretty new to jQuery.
I would like to get each .figure and assign them an inline style where the value is contained inside the child element via a custom data- attribute :
<div>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-01-thumbnail.png" src="images-01.png" />
</div>
<div class="content">
<h3>Sale</h3>
<h4>Discover our latest styles</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-02-thumbnail.png" src="images-02.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-03-thumbnail.png" src="images-03.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
</div>
In other words, the results would be :
...
<div class="figure" style="background: url(images-01-thumbnail.png);">
...
<div class="figure" style="background: url(images-02-thumbnail.png);">
...
<div class="figure" style="background: url(images-03-thumbnail.png);">
...
Also, I'm always ready something about jQuery so if you have any books about JavaScript or jQuery to suggest, that is always appreciated.
You can iterate over all .picture elements, find the image descendant and read its data attribute:
$('.figure').css('background', function() {
return 'url(' + $(this).children('img').data('thumbnail') + ')';
});
Some methods, like .css even accept functions so that you can iterate over the selected elements implicitly.
Reference: .css, .children, .data
you can iterate over each item with the class thumbnail and set the css property to the closet div.
$('.thumbnail').each(function() {
var $this = $(this),
$background = $this.data('thumbnail');
$this.closest('.figure').css({background : $background} )
});
This should work
$("[data-thumbnail]").each(function ()
{
var $this = $(this), url = $this.data("thumbnail");
$this.parents(".figure").css("background-image", 'url("' + url + '")');
});
How about this (Working code example: http://jsfiddle.net/jpbH2/2/):
var pathToImages = "/";
$(".figure img").each(function(){
$(this).parent().css({"background": "url(" + pathToImages + $(this).data('thumbnail') +")"})
});
Edit
I actually didn't notice the data-thumbnail. Edited my answer above

Categories

Resources