This question already has answers here:
Change the image source on rollover using jQuery
(14 answers)
Closed 8 years ago.
I am very new to javascript and jquery so I could use some help.
How can I change the image src when I hover every image? For example when I hover the facebook-icon it changes, when I hover google+ image/icon it changes to another image that i have etc.
<div class="social-icons wrapper-social">
<a href="#" target="_blank">
<img id="facebook" src="images/Facebook.png" />
</a>
<a href="#" target="_blank">
<img id="google" src="images/Google+.png" />
</a>
<a href="#" target="_blank">
<img id="twitter" src="images/Tweeter.png" />
</a>
<a href="#" target="_blank">
<img id="pinterest" src="images/Pinterest.png" />
</a>
</div>
Thanks in advance!
$(document).ready(function() {
$("#facebook").hover(function() {
$(this).attr("src","new src");
});
});
If you want to retain previous image then use below code
var old_src="";
$(document).ready(function() {
$("#facebook").mouseover(function() {
old_src = $(this).attr("src");
$(this).attr("src","new src");
}).mouseout(function() {
$(this).attr("src",old_src);
});
})
Here is the updated and working code.
HTML Part-
<div class="social-icons wrapper-social">
<a href="#" target="_blank">
<img class="imgRes" id="facebook" src="images/Facebook.png" />
</a>
<a href="#" target="_blank">
<img class="imgRes" id="google" src="images/Google+.png" />
</a>
<a href="#" target="_blank">
<img class="imgRes" id="twitter" src="images/Tweeter.png" />
</a>
<a href="#" target="_blank">
<img class="imgRes" id="pinterest" src="images/Pinterest.png" />
</a>
</div>
JavaScript Part-
function handleImageHover(e) {
if(e.target.id == "facebook") {
e.target.src = "/images/newFacebookImage.png";
}
if(e.target.id == "google") {
e.target.src = "/images/newGoogleImage.png";
}
if(e.target.id == "twitter") {
e.target.src = "/images/newTwitterImage.png";
}
if(e.target.id == "pinterest") {
e.target.src = "/images/newPinterestImage.png";
}
}
var imagesArray = document.getElementsByClassName("imgRes");
for (img = 0; img < imagesArray.length; img++) {
imagesArray[img].addEventListener("mouseover", handleImageHover, false);
}
Just following up on WisdmLabs answer.
Here is the DEMO
Here is the jQuery
$(document).ready(function(){
$("#facebook").hover(function(){
$(this).attr("src","New src");
},function(){
$(this).attr("src","Original src");
});
});
Here is a solution created using CSS sprites which NATH was talking about. It will reduce the load on the sever as the CSS sprite will be loaded only once and then it can be used any number of times for your hover effects.
CSS Sprite DEMO
There is no need of JavaScript/Jquery for this, this can be achieved by pure css.
CSS
<style type="text/css">
.social-icons a{
width: 35px;
height: 35px;
display: inline-block;
}
.facebookIcon {
background-image:url('images/Facebook.png');
}
.facebookIcon:hover {
background-image:url('images/FacebookHover.png');
}
.googleIcon {
background-image:url('images/Google+.png');
}
.googleIcon:hover {
background-image:url('images/GoogleHover.png');
}
.twitterIcon {
background-image:url('images/Tweeter.png');
}
.twitterIcon:hover {
background-image:url('images/TweeterHover.png');
}
.pinIcon {
background-image:url('images/Pinterest.png');
}
.pinIcon:hover {
background-image:url('images/PinterestHover.png');
}
</style>
HTML
<div class="social-icons wrapper-social">
<a href="#" target="_blank" class="facebookIcon">
</a>
<a href="#" target="_blank" class="googleIcon">
</a>
<a href="#" target="_blank" class="twitterIcon">
</a>
<a href="#" target="_blank" class="pinIcon">
</a>
</div>
Related
I have a few div's with class ".web-item" containing images. I go through them with a for loop and put an addEventListener (mouseover) on all the iterations and try to change the styling of each element (always the hovered element's style). But as I hover over an element, the styling of all the elements changes following the hovered element.
This is my JavaScript code:
let webItems = document.querySelectorAll(".web-item");
let i = 0;
for (let i = 0; i < webItems.length; i++) {
webItems[i].addEventListener("mouseover", function() {
webItems[i].style.filter = "brightness(30%)";
webItems[i].children[1].style.display = "block";
});
};
And the HTML:
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-a"] ?>
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-b"] ?>
</div>
</div>
How could I achieve that only the actually hovered element's styling changes? I would be really grateful for your help.
Only the styling of the hovered element will change - but if you hover over another element afterwards (like if you're moving the mouse quickly), that element's style will change too. You don't have any "stop hovering" functionality at the moment - if the mouse hovers over something, that element's style will stay changed until the page is reloaded.
let webItems = document.querySelectorAll(".web-item");
let i = 0;
for (let i = 0; i < webItems.length; i++) {
webItems[i].addEventListener("mouseover", function() {
webItems[i].style.filter = "brightness(30%)";
webItems[i].children[1].style.display = "block";
});
};
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-a"] ?>
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-b"] ?>
</div>
While you could add a mouseout listener, this can be achieved with only CSS and :hover:
.web-item-caption {
display: none;
}
.web-item:hover {
filter: brightness(30%)
}
.web-item:hover > .web-item-caption {
display: block;
}
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
text 1
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
text 2
</div>
I would like to toggle the src of the specific image element clicked. But, only for that image. In other words, only toggle the one clicked. If clicked again then change back. How can I do this with jQuery or JavaScript. The code can be seen here: https://codepen.io/centem/pen/NgKEmG
<!--
When image clicked change image to:
https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png
-->
<ul class="list-unstyled">
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>
</ul>
Here is my jquery:
function handler( event ) {
var target = $( event.target );
if ( target.is( "img" ) ) {
target.src().toggle(
"https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
}
}
Thank you.
You can add click event on img that exist in ul and toggle src of them by saving in data attribute. For toggling you need to save main src of image that can be saved as data-src (or anything else), And you need a flag for state of image like data-clicked (or anything else).
$('ul.list-unstyled li img').on('click', function(){
var clicked = $(this).data('clicked');
if(clicked === '1') {
$(this).attr('src', $(this).data('src'))
$(this).data('clicked', '0')
} else {
$(this).data('src', $(this).attr('src'))
$(this).attr('src', "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
$(this).data('clicked', '1')
}
})
img {
height: 25px;
padding-right: 4px;
}
li {
margin: 4px;
clear: both;
}
li:nth-child(odd) {
background: #f0f0f5;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--
When image clicked change image to:
https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png
-->
<ul class="list-unstyled">
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>
<li>Username<span class="pull-right">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right">
<img src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
<img src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li></li>
</ul>
What you need to use is jquery's attr() function
Give your image a class name then you can change the src in jQuery by:
$(".image1").attr("src","https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
And to attach it to a click event
$(".image1").click(function(){
$('.image1').attr('src','https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png');
});
add an ID to your image and then try this:
$(function() {
$("#yourImage").onClick(function() {
$(this).attr("src", "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
});
});
Alternatively, you can change the image depending on the source like this:
$(function() {
$("img").onClick(function() {
if ($(this).attr("src") == "OriginalSource")
$(this).attr("src", "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png");
});
});
I have different a-tags which gets generated dynamically. Each link will generate an own div with different contents so each div has an individual content as well as an individual height.
Now I would like to achieve that when hovering an a the matching div will be shown. The div then should be shown at the mouse position and should be position from bottom to top direction so that the div is "growing in upward direction" because the links are on the bottomside of the page.
Here is what the code is look like ($z is a counter):
<a href="<?php echo $link_djv;?>" class="rsshover" id="djvl_<?php echo $z;?>" target="_blank">
<li>
<p class="headline"><?php echo $title_djv;?></p>
</li>
</a>
<div class="preview" id="djvd_<?php echo $z;?>">
<?php echo $description_djv;?>
</div>
I read already through different threads but wasn't able to find a proper way on how to solve this issue. Thanks in advance.
Run Snippet
This is a basic version of what you need. obviously the animation needs work but should give you a good starting point.
class ToolTipControl {
constructor () {
this.xCoordinate;
this.yCoordinate;
this.links = document.querySelectorAll('a');
this.addEventListeners();
this.activeLink = false;
}
addEventListeners () {
for (let link of this.links) {
link.addEventListener('mouseenter', (e) => this.handleMouseEnter(e));
link.addEventListener('mouseleave', (e) => this.handleMouseLeave(e));
}
document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
}
handleMouseMove (event) {
this.xCoordinate = event.pageX;
this.yCoordinate = event.pageY;
if (this.activeLink) {
this.activeLink.style.top = `${this.yCoordinate}px`;
this.activeLink.style.left = `${this.xCoordinate}px`;
}
}
handleMouseEnter (event) {
this.activeLink = event.target.nextElementSibling;
this.activeLink.style.maxHeight = '50px';
}
handleMouseLeave (event) {
let targetsContent = event.target.nextElementSibling;
targetsContent.style.maxHeight = 0;
this.activeLink = false;
}
}
new ToolTipControl();
.preview {
position: absolute;
max-height: 0;
overflow: hidden;
transition: max-height 0.6s ease;
}
li {
list-style: none;
}
a {
padding: 20px;
margin: 20px;
color: white;
display: block;
background-color: grey;
width: 100px;
}
<a href="/" class="rsshover" id="djvl_123" target="_blank">
<li>
<p class="headline">some title</p>
</li>
</a>
<div class="preview" id="djvd_098">
content 1
</div>
<a href="/" class="rsshover" id="djvl_123" target="_blank">
<li>
<p class="headline">some title</p>
</li>
</a>
<div class="preview" id="djvd_098">
content 2
</div>
<a href="/" class="rsshover" id="djvl_123" target="_blank">
<li>
<p class="headline">some title</p>
</li>
</a>
<div class="preview" id="djvd_098">
content 3
</div>
You're going to need to add a mouse over event of your link and then a javascript function to show your div in the right location. Then you'll need a mouseout even to hide the div again.
what I would start with is change your php code to be:
<a href="<?php echo $link_djv;?>" class="rsshover" onmouseover="showDiv('<?php echo $z;?>');" onmouseout="hideDiv('<?php echo $z;?>');" id="djvl_<?php echo $z;?>" target="_blank">
<li>
<p class="headline"><?php echo $title_djv;?></p>
</li>
</a>
<div class="preview" id="djvd_<?php echo $z;?>" style="display:none;">
<?php echo $description_djv;?>
</div>
Then add a javascript function:
<script>
function showDiv(counter) {
document.getElementById('djvd_' + counter).style.display = 'block';
// this is where you'd position your div location
}
function hideDiv(counter) {
document.getElementById('djvd_' + counter).style.display = 'none';
}
</script>
You can use CSS by putting the div.preview inside the a.rsshover
.rsshover .preview {
display: none;
}
.rsshover:hover .preview {
display: block;
}
<a href="#" class="rsshover" target="_blank">
<li>
<p class="headline">1</p>
</li>
<div class="preview">
ONE
</div>
</a>
<a href="#" class="rsshover" target="_blank">
<li>
<p class="headline">2</p>
</li>
<div class="preview">
TWO
</div>
</a>
<a href="#" class="rsshover" target="_blank">
<li>
<p class="headline">3</p>
</li>
<div class="preview">
THREE
</div>
</a>
I don't understand how exactly do you want your preview to be displayed, but this should help you.
(function($) {
var $currentElement;
$('.rsshover').on('mouseenter', function(e) {
$currentElement = $('#djvd_' + $(this).attr('id').substr(5));
$currentElement.css({
position: 'absolute',
display: 'block',
top: e.clientY + 'px',
left: e.clientX + 'px'
});
}).on('mouseleave', function() {
$currentElement.hide()
})
})(jQuery)
.preview {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="rsshover" id="djvl_1" target="_blank">
<li>
<p class="headline">Headline</p>
</li>
</a>
<div class="preview" id="djvd_1">
Description 1
</div>
Also, please don't put <li> tags inside anchor <a>.
I recently made a jquery code that should hides an element if it's href is equal to another element's but i can't be able to make it work...
jsfiddle
HTML
<div class="a">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb b">
<a href="2">
<img scr="b">
</a>
</div>
CSS
.a{width:400px;height:100px;background-color:black;}
.thumb{width:400px;height:100px;background-color:green;}
.b{background-color:yellow;}
JQUERY
var mainhref = $(".a a").attr('href');
if($("a", this).attr('href') == mainhref ) {
$(".a").hide();
}
else {
$(".a").show
}
Using plain javascript :D
let ar = document.getElementsByTagName('a'),
holdarray = [];
Array.from(ar, elem => {
if(holdarray.includes(elem.getAttribute('href')))
elem.parentNode.style.display = 'none'
else
holdarray.push(elem.getAttribute('href'))
})
.a { width:400px;height:100px;background-color:black; }
.thumb { width:400px;height:100px;background-color:green; }
.b { background-color:yellow; }
<div class="a" >
</div>
<div class="thumb">
</div>
<div class="thumb b">
</div>
You can try like this, only check for thumb class then it will hide specific div which contain same href
var mainhref = $(".a a").attr('href');
$('.thumb a').each(function(){
if($(this).attr('href') == mainhref)
{
$(this).parents('.thumb').hide();
}
});
Just select by that href (and parent not containing the base div's class 'a') and hide it
$('a[href="'+mainhref+'"]').parent(":not(.a)").hide();
var mainhref = $(".a a").attr('href');
var parentDiv = $('a[href="'+mainhref+'"]').parent(":not(.a)").hide();
.a{width:400px;height:100px;background-color:black;}
.thumb{width:400px;height:100px;background-color:green;}
.b{background-color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a" >
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb b">
<a href="2">
<img scr="b">
</a>
</div>
Try something like this with Jquery.
Loop on each a and store the href. Select all <a> but first with same href and hide the parent
$("a").each(function(){
var href= $(this).attr("href");
$("a[href='"+href+"']").not(":first").parent().hide();
});
.a{width:400px;height:100px;background-color:black;}
.thumb{width:400px;height:100px;background-color:green;}
.b{background-color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb">
<a href="1">
<img scr="a">
</a>
</div>
<div class="thumb b">
<a href="2">
<img scr="b">
</a>
</div>
You should loop through all elements.
$('a').each(function(){
if($(this).attr('href') == mainhref){
$(this).hide();
}
});
$('a').each(function(){
if($(this).attr('href') == mainhref){
$(this).hide();
}
});
Here's a trick, using the radio:checked.
$($("a").toArray().reverse()).each(function(index, el){
var href = $(el).attr('href');
$(el).parent().before('<input type="radio" name="' + href + '" class="hidden" checked />');
})
The reason that I use reverse is that I want the first a tag to remain showing. If you want the last a tag to remain, you can just use $('a') instead of $($("a").toArray().reverse())
css:
.hidden { display:none };
input[type=radio]+ div a { display: none };
input[type=radio]:checked + div a { display: block };
With this trick, you can make all the a tag with a unique href. Hope it can help you.
I'm a trainee and actually I'm working on a web shop.
Now I got the problem that I have multiple images placeholders (image_1-6) for our article images. Problem now is, if the article only has 2 images the placeholders for the other 4 are still there. So is there any possibility to hide them if the src is empty or a parameter defined by me?
Here is the code snippet:
<div class="sideimg grid_2">
<div id="image_1" class="lb_thumb">
<a href="javascript:;" onmouseover="swapImage('Bild1','','http://media-11teamsports.de/ArticleBig/[ArtikelOnlinebezeichnungD.Bild1]',1)" onmouseout="swapImgRestore()">
<img class="lb_detailimg" src="http://media-11teamsports.de/ArticleSmall/[ArtikelOnlinebezeichnungD.Bild1]"id=image1 name="Bild1" alt="Bild1" id="Bild2" />
</a>
</div>
<div id="image_2" class="lb_thumb">
<a href="javascript:;" onmouseover="swapImage('Bild1','','http://media-11teamsports.de/ArticleBig/[ArtikelOnlinebezeichnungD.Bild2]',1)" onmouseout="swapImgRestore()">
<img class="lb_detailimg" src="http://media-11teamsports.de/ArticleSmall/[ArtikelOnlinebezeichnungD.Bild2]" id=image2 name="Bild2" alt="Bild2" id="Bild2" />
</a>
</div>
<div id="image_3" class="lb_thumb">
<a href="javascript:;" onmouseover="swapImage('Bild1','','http://media-11teamsports.de/ArticleBig/[ArtikelOnlinebezeichnungD.Bild3]',1)" onmouseout="swapImgRestore()">
<img class="lb_detailimg" src="http://media-11teamsports.de/ArticleSmall/[ArtikelOnlinebezeichnungD.Bild3]" id=image3 name="Bild3" alt="Bild3" id="Bild2" />
</a>
</div>
<div id="image_4" class="lb_thumb">
<a href="javascript:;" onmouseover="swapImage('Bild1','','http://media-11teamsports.de/ArticleBig/[ArtikelOnlinebezeichnungD.Bild4]',1)" onmouseout="swapImgRestore()">
<img class="lb_detailimg" src="http://media-11teamsports.de/ArticleSmall/[ArtikelOnlinebezeichnungD.Bild4]" id=image4 name="Bild4" alt="Bild4" id="Bild2" />
</a>
</div>
<div id="image_5" class="lb_thumb">
<a href="javascript:;" onmouseover="swapImage('Bild1','','http://media-11teamsports.de/ArticleBig/[ArtikelOnlinebezeichnungD.Bild5]',1)" onmouseout="swapImgRestore()">
<img class="lb_detailimg" src="http://media-11teamsports.de/ArticleSmall/[ArtikelOnlinebezeichnungD.Bild5]" id=image5 name="Bild5" alt="Bild5" id="Bild2" />
</a>
</div>
<div id="image_6" class="lb_thumb">
<a href="javascript:;" onmouseover="swapImage('Bild1','','http://media-11teamsports.de/ArticleBig/[ArtikelOnlinebezeichnungD.Bild6]',1)" onmouseout="swapImgRestore()">
<img class="lb_detailimg" src="http://media-11teamsports.de/ArticleSmall/[ArtikelOnlinebezeichnungD.Bild6]" id=image6 name="Bild6" alt="Bild6" id="Bild2" />
</a>
</div>
</div>
Here is the live version(wip): http://www.ebay.de/itm/Jako-Tape-10-Meter-2-5-cm-breit-Rot-F01-/272269970423?
All I know about html css and js I learned by myself so I hope the snippet is fine.
So as you can see I have 6 images with js image swap. The only left problem is that our database don't contains an image for every placeholder, so if there are only 4 pictures there are still 2 empty boxes. So how can i get rid of them?
Thanks all for your help and excuse my english I'm from Germany.
You can try using the CSS selector for html attributes like this:
.lb_detailimg[src]{
(Whatever css u need goes here)
display: block;
}
.lb_detailimg{
display: none;
}
If any <img> of class lb_detailimg does not have a src attribute it will not be displayed.
You could also use a keyword in the src attribute to make this happen, like this:
.lb_detailimg{
(Whatever css u need goes here)
}
.lb_detailimg[src=keyword]{
display: none;
}
EDIT:
As you cannot give style to a parent element in CSS here is a JS snippet that should work fine:
window.onload = function(){
var img_containers = document.getElementsByClassName("lb_thumb");
for(var i=0; i<img_containers.length;i++){
if(img_containers[i].getElementsByTagName("img")[0].src.indexOf("keyword") > -1){
img_containers[i].style.display = "none";
}
}
}
At line 4 in the if ==> .indexOf("yourKeyWordHere")