Change image when div click - javascript

I have a div act like button that contain an image. I want when I click the div the image inside it will change I put a jquery but my jquery only work in 1 way it can switch to second image but cant switch back to first image.
HTML :
<div class="post-like m-30">
<img class="img-responsive" src="img/like.png" alt="">
<h4 class="bold text-center capital">appreciate this!</h4>
</div>
CSS :
.post-like{
cursor: pointer;
}
.post-like img{
margin: auto;
}
JS :
$(document).ready(function() {
$('.post-like').click(function(){
$(".post-like img").attr('src',"img/like.jpg");
return false;
});
});
Can you teach me why my jquery didnt work?

To toggle between the both src attributes, you could add condition in your click event :
$(document).ready(function() {
$('.post-like').click(function(){
var src = $(".post-like img").attr('src');
if(src=="https://upload.wikimedia.org/wikipedia/commons/2/2f/MRT_Singapore_Destination_1.png")
$(".post-like img").attr('src',"https://upload.wikimedia.org/wikipedia/commons/1/10/MRT_Singapore_Destination_2.png");
else
$(".post-like img").attr('src',"https://upload.wikimedia.org/wikipedia/commons/2/2f/MRT_Singapore_Destination_1.png");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-like m-30">
<img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/2/2f/MRT_Singapore_Destination_1.png" alt="">
<h4 class="bold text-center capital">appreciate this!</h4>
</div><!-- post-like -->

Grab the value of the src attribute and store it in a variable. Use this variable as your reference in an if statement to determine which image to switch to:
$(document).ready(function() {
$('.post-like').click(function(){
var img=$(this).attr('src');
if(img=="img/like.jpg"){
$(".post-like img").attr('src',"img/like.jpg");
return false;
}else{
$(".post-like img").attr('src',"img/otherimage.jpg");
return false;
}
});
});

There was nothing wrong with your code, it changed the source just fine.
In order to create a 'click to toggle'-flow, you need to know both sources, I tend to do this by having two variables (one with the 'special' source and one empty, which is set on first use).
$(function() {
var specialSrc = 'http://lorempixel.com/image_output/nightlife-q-g-160-100-10.jpg',
img = $('.post-like img'),
normalSrc;
$('.post-like').click(function(){
var src = img.attr('src');
if (!normalSrc) {
normalSrc = src;
}
img.attr('src', src === normalSrc ? specialSrc : normalSrc);
return false;
});
});
.post-like{
cursor: pointer;
}
.post-like img{
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-like m-30">
<img class="img-responsive" src="http://lorempixel.com/image_output/nightlife-q-c-160-100-4.jpg" alt="">
<h4 class="bold text-center capital">appreciate this!</h4>
</div><!-- post-like -->
I've also stored the image in the img variable, so you don't need to look for it every click, and I've replace $(document).ready(function() {..}) with the shorter syntax $(function() {..}) which does the same thing)

make it simpler and do toggle
$(".post-like").click(function() {
$(this).find('img').toggle();
});
TOGGLE

Related

Toggle images hide/visible in HTML

Here's the thing, I want some of the pictures in my HTML file to be hidden at first leaving a black at its position. And it's shown after clicking on it. I can put js code in my layout file but to keep the code clean and extremely readable, there shouldn't be div span tags or id or class, just add parameters like 'onclick' in img tags.
Current code:
<script type="text/javascript">
function toggle_visibility() {
if ( this.style.visibility == 'hidden' )
this.style.visibility = 'visible';
else
this.style.visibility = 'hidden';
}
</script>
<img onclick="toggle_visibility();" src="IMG.jpg"/>
Add specific class to each element that needs that functionality. In my example this class is 'image'.
Also you need to have draggable set to false for images, else you can still see the image when dragging.
document.addEventListener('click', function(e) {
if (e.target.classList.contains('image')) {
e.target.style.filter = 'brightness(100%)';
}
});
img.image {
height: 100px;
filter: brightness(0%);
}
<img class="image" src="https://stepupandlive.files.wordpress.com/2014/09/3d-animated-frog-image.jpg"/ draggable="false">
<img class="image" src="https://dictionary.cambridge.org/images/thumb/chick_noun_002_06563.jpg?version=4.0.44"/ draggable="false">

How to efficiently create 100's of toggle image buttons?

I was looking for a way to change image A to B and B to A by just
clicking them.
So far, this is what I'm using.
<img id="pixelbutton" src="images/pixelbutton.png" />
<img id="pixelbutton2" src="images/pixelbutton_press.png" style="display: none;" />
<script type="text/javascript">
$(document).ready(function(){
$("#pixelbutton").click(function(){
$("#pixelbutton").css({'display':'none'})
$("#pixelbutton2").css({'display':'block'});
})
$("#pixelbutton2").click(function(){
$("#pixelbutton2").css({'display':'none'})
$("#pixelbutton").css({'display':'block'});
})
})
</script>
The script works well for a pair of image.
Now if I have 100 pair of image.
"A <--> B"
"C <--> D"
"E <--> F"
and so on...
Do I have to copy the body HTML and script 100 times and change their ID+URL or there is another more efficient way?
To create hundreds of them... First, use a class.
Then, use a data attribute to store the "alternate" URL.
<img class="pixelbutton" src="images/pixelbutton.png" data-altsrc="images/pixelbutton_press.png"/>
<script type="text/javascript">
$(document).ready(function(){
$(".pixelbutton").click(function(){
// Get the two values
var src = $(this).attr("src");
var altSrc = $(this).data("altsrc");
// Switch them
$(this).attr("src",altSrc).data("altsrc",src);
});
})
</script>
This will work for thousands of .pixelbutton...
;)
EDIT
As per this other .data() documentation, (I wonder why there's two different documentation pages...) the data-* have to be lowercase... Because when trying to get altSrc, it is interpreted as alt-src.
I just learned that... That is quite a strange new standard, from jQuery 3.
So here is your CodePen updated.
You could probably set a naming pattern and use delegation to make an event handler on the images' container.
You could check if the event's target is an image and retrieve its id. Using that id, you could use the pattern you've set to change the images interchangeably.
There are multiple solutions to this, but this is by far the simplest approach:
Wrap your image pairs in a parent <div>
Use .toggleClass() to toggle a class, say .hide, in the images in the element
This solution assumes that you have images in pairs :) see proof-of-concept example:
$(document).ready(function() {
$('img').click(function() {
console.log($(this).siblings());
$(this).add($(this).siblings()).toggleClass('hide');
});
});
/* For layout only */
div {
display: inline-block;
}
/* Used to hide image */
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
Try this one:
jQuery(document).ready(function($) {
var $imgBlock = $('#images');
var html = '';
var imgArr = [
'http://i0.wallpaperscraft.com/image/surface_shape_metal_116716_200x300.jpg',
'http://i0.wallpaperscraft.com/image/universe_space_face_rocket_116714_200x300.jpg',
'http://i0.wallpaperscraft.com/image/letter_surface_wooden_116674_200x300.jpg',
'http://i0.wallpaperscraft.com/image/mountains_lake_reflection_116663_200x300.jpg',
'http://i1.wallpaperscraft.com/image/leaf_drops_surface_116678_200x300.jpg',
'http://i1.wallpaperscraft.com/image/candle_spruce_christmas_decoration_116684_200x300.jpg'
];
$.each(imgArr, function(index, url) {
html += (index % 2 === 0) ? '<div>' : '';
html += '<img src="' + url + '"/>';
html += (index % 2 === 1 || index === imgArr.length - 1) ? '</div>' : '';
});
$imgBlock.append(html);
$imgBlock.on('click', 'img', function(e) {
$(this).parent('div').find('img').removeClass('red');
$(this).addClass('red');
});
});
img {
border: 2px solid #ccc;
}
.red {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="images"></div>

Gif wont animate on hover

I saw this post and I tried to replicate the code: Stop a gif animation onload, on mouseover start the activation. I can't seem to get it to work though. My goal is to swap the image with a gif on hover. Does someone know why the image isn't swapping?
$(document).ready(function() {
$("#imgAnimate").hover(
function() {
$(this).attr("src", "images/portfolio/form.gif");
},
function() {
$(this).attr("src", "images/portfolio/form.jpg");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="large-12 medium-12 small-12 columns portfolio-pic animated slideInUp">
<div data-content="Project 1" class="image">
<a class="a-block" href="#">
<img id="imgAnimate" src="images/portfolio/form.jpg">
</a>
</div>
</div>
</div>
Here is a live link to my example: http://fosterinnovationculture.com/dcc/index.html
From what your page is saying jQuery is undefined. So either you are trying to execute jquery code before jquery is executed.
I executed this code on your site just to testing things out and it seems to be working
function mousein () {
$(this).attr("src", "images/portfolio/form.gif");
console.log('hello')
}
function mouseout () {
$(this).attr("src", "images/portfolio/form.jpg");
}
console.log($('#imgAnimate').hover(mousein, mouseout));
I did notice though that because of some styling issues the hover was never actually hitting the img it was actually hitting the .image:after css psuedo selector so you need to reorganize your html or change the way you select the element you want to switch the src of.
just to test in your html move the image outside of
<div class="image">image</div>
Yes its correct as told by #madalin ivascu, you need to add jquery at header and it will work.
Like this,
HTML
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#imgAnimate").hover(
function() {
$(this).attr("src", "banana.gif");
},
function() {
$(this).attr("src", "banana.png");
});
});
</script>
</head>
<body>
/* include your html part here */
<a class="a-block" href="#">
<img id="imgAnimate" src="banana.png" alt="">
</a>
</body>
Try this, Instead of using hover, try that using mouseenter and mouseleave.
$(document).ready(function(){
$(".row").find('img').mouseenter(function(){
if($("#imgAnimate").attr('src','form.jpg')){
$("#imgAnimate").attr('src','form.gif');
}
$(this).mouseleave(function(){
if($("#imgAnimate").attr('src','form.gif')){
$("#imgAnimate").attr('src','form.jpg');
}
});
});
});

Swap images on hover with fade

I'm attempting to swap out an image on hover with a fade in / fade out effect. The jQuery below works well because it lazy loads the hover image.
The first example shows a flash of white as the original image is replaced with the new image as it fades in. The second example shows the desired fade in effect by setting the background but somehow loses the fade out effect.
HTML:
<img class="imageHoverLoad lazy"
data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg"
data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />
jQuery:
$('.imageHoverLoad').mouseenter(function() {
var elem = $(this);
elem.attr('src', elem.attr('data-hover')).hide().fadeIn(400);
});
$('.imageHoverLoad').mouseleave(function() {
var elem = $(this);
elem.attr('src', elem.attr('data-original')).hide().fadeIn(400);
});
Codepen:
http://codepen.io/anon/pen/KVQavM
You're replacing the src before your transition, so there's no time to fade out. And you need to specify the fadeOut and wait for the animation promise to resolve before continuing:
$(function() {
$("img.lazy").lazyload();
});
$('.imageHoverLoad').mouseenter(function() {
var elem = $(this);
elem.fadeOut(400).promise().done(function() {
elem.attr('src', elem.attr('data-hover')).fadeIn(400);
});
});
$('.imageHoverLoad').mouseleave(function() {
var elem = $(this);
elem.fadeOut(400).promise().done(function() {
elem.attr('src', elem.attr('data-original')).fadeIn(400);
});
});
.swap-image {
width: 300px;
height: 300px;
margin-bottom: 100px;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.js"></script>
<div class="swap-image">
<img class="imageHoverLoad lazy" data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg" data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />
</div>
<div class="swap-image" style="background: url(http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg) no-repeat;">
<img class="imageHoverLoad lazy" data-original="http://decoymagazine.ca/wp-content/uploads/2012/06/red-300x300.jpg" data-hover="http://images.wolfordshop.com/images/colors/thumbs/5635.jpg" />
</div>

Make an image visible when I hover over another

Essentially I have an interactive map which contains 4 div statements each of which contains an image of an island. I would like to create an on hover event which will display a corresponding sailing timetable depending on which image the user hovers. e.g. island 1 should display timetable 1.
I have the following code so far and ideally I am looking for a javascript or css solution:
<div class="Map">
<div id="Island_Morar">
<img src="images/IsleOfMorar.jpg"/>
</div>
<div id="Island_Rum">
<img src="images/IsleOfRum.jpg"/>
</div>
<div id="Island_Eigg">
<img src="images/IsleOfEigg.jpg"/>
</div>
<div id="Island_Muck">
<img src="images/IsleOfMuck.jpg"/>
</div>
</div>
<img id="TimetableEigg" src="images/TimetableEigg.jpg">
any help is appreciated.
You need some different markup if you want a plain css solution. If you want to have different timetables for each hover you should go with something like this:
markup
<div class="tt-container" id="Island_Rum">
<img src="images/IsleOfRum.jpg"/>
<img class="timetable" src="images/TimetableRum.jpg">
</div>
<div class="tt-container" id="Island_Eigg">
<img src="images/IsleOfEigg.jpg"/>
<img class="timetable" src="images/TimetableEigg.jpg">
</div>
<div class="tt-container" id="Island_Muck">
<img src="images/IsleOfMuck.jpg"/>
<img class="timetable" src="images/TimetableMuck.jpg">
</div>
</div>
css
.timetable {
display : none;
}
.tt-container:hover .timetable {
display : block;
}
That should do the trick
If you want to keep your current HTML code, I'd make three image blocks for timetables, and initially set them all to display: none; and add onmouseover event handlers to island elements which would contain Javascript statement which will set disply: block; on appropriate timetable.
Something like this:
<div class="Map">
<div id="Island_Morar" onmouseover="document.getElementById('TimetableEigg1').style.display = 'block';">
<img src="images/IsleOfMorar.jpg"/>
</div>
<div id="Island_Rum" onmouseover="document.getElementById('TimetableEigg2').style.display = 'block';" >
<img src="images/IsleOfRum.jpg"/>
</div>
<div id="Island_Eigg" onmouseover="document.getElementById('TimetableEigg3').style.display = 'block';" >
<img src="images/IsleOfEigg.jpg"/>
</div>
<div id="Island_Muck" onmouseover="document.getElementById('TimetableEigg4').style.display = 'block';" >
<img src="images/IsleOfMuck.jpg"/>
</div>
</div>
<img id="TimetableEigg1" src="images/TimetableEigg1.jpg">
<img id="TimetableEigg2" src="images/TimetableEigg2.jpg">
<img id="TimetableEigg3" src="images/TimetableEigg3.jpg">
<img id="TimetableEigg4" src="images/TimetableEigg4.jpg">
Seems you barely know the basics of HTML and already trying to jump too deep. External libraries will help you and speed up your progress. I see people gave you CSS solutions so here is a JS solution.
First thing is download the well known JS library called jQuery.
then load this file to your page and add a script at the bottom of your body tag:
$("div.map").on("mouseover", "#Island_Morar", function(e) {
$(this).show(); // option one
//$(this).addClass("class-name"); // option two
}).on("mouseout", "#Island_Morar", function(e) {
$(this).hide(); // option one
//$(this).removeClass("class-name"); // option two
});
With this script you can do whatever you want, for example - use the second option of adding and removing classes in order to animate your Timetables (see Example).
Possible CSS / JQuery solution:
$(".Map a").hover(
function() {
$('#' + $(this).attr('class')).show();
}, function() {
$('#' + $(this).attr('class')).hide();
}
);
.timetables img { display:none; }
<div class="Map">
<a href="#" class="islandmorar">
<img src="images/IsleOfMorar.jpg"/>
</a>
<a class="islandrum">
<img src="images/IsleOfRum.jpg"/>
</a>
<a class="islandeigg">
<img src="images/IsleOfEigg.jpg"/>
</a>
<a class="islandmuck">
<img src="images/IsleOfMuck.jpg"/>
</a>
</div>
<div class="timetables">
<img id="islandmorar" src="images/TimetableEigg.jpg"/>
<img id="islandrum" src="images/TimetableEigg.jpg"/>
<img id="islandeigg" src="images/TimetableEigg.jpg"/>
<img id="islandmuck" src="images/TimetableEigg.jpg"/>
</div>
Pure CSS solution but you need to place the large image in .main div
the first image will be displayed first and will change on hover on other images and when you leave move out of the main div it will show the first image
Note: used random images
.Map > div {
display: inline-block;
}
img.two,
img.three,
img.four,
#Island_Rum:hover ~ img.one,
#Island_Muck:hover ~ img.one,
#Island_Eigg:hover ~ img.one {
display: none;
}
img.one {
display: block;
}
#Island_Morar:hover ~ img.one {
display: block;
}
#Island_Rum:hover ~ img.two {
display: block;
}
#Island_Eigg:hover ~ img.three {
display: block;
}
#Island_Muck:hover ~ img.four {
display: block;
}
<div class="Map">
<div id="Island_Morar">
<img src="http://placeimg.com/100/100/any/animals" />
</div>
<div id="Island_Rum">
<img src="http://placeimg.com/100/100/any/arch" />
</div>
<div id="Island_Eigg">
<img src="http://placeimg.com/100/100/any/nature" />
</div>
<div id="Island_Muck">
<img src="http://placeimg.com/100/100/any/tech" />
</div>
<img class="one" src="http://placeimg.com/400/400/any/animals" />
<img class="two" src="http://placeimg.com/400/400/any/arch" />
<img class="three" src="http://placeimg.com/400/400/any/nature" />
<img class="four" src="http://placeimg.com/400/400/any/tech" />
</div>
Don't put class="map" to the wrapper div, give it to every div with id beginning with "Island_...".
Do the same with your timeTable images, give them a class "timeTable".
Put this before your "head" end tag :
<script>
"use strict";
//wait for every element to be loaded
window.onload = function(){initialization();}
</script>
Then, put this before your "body" end tag :
<script>
"use strict";
//first create a function that hides elements with class 'timeTable'
function hide(elements){
var htmlClass = document.getElementsByClassName(elements);
//hide every element with class
for (var i = 0 ; i < htmlClass.length ; i++){
htmlClass[i].style.display = "none";
htmlClass[i].style.visibility = "hidden";
}
}
//create a function that show only the timeTable you want
function show(element){
document.getElementById(element).style.display = "block";
document.getElementById(element).style.visibility = "visible";
}
function initialization(){
//replace 'someMapId' with the id of the image you are hovering
//replace 'someTimeTableId' with the id of the image you want to show
//replace 'timeTable' with the name of a class you want to hide
document.getElementById("someMapId").onmouseover = function(){
hide("timeTable");
show("someTimeTableId");
}
//repeat these 3 lines for every image the user will hover
}
</script>
Don't forget the quotes when using the functions.
You should use css for styling and javascript for interactions.
You don't need jQuery for basic scripts like that, it only slows page loading and keeps you away from learning basic javascript.
(Ok, I edited mistakes, now it works ;)
jsFiddle

Categories