Mouse / Hover over image change parent image src - javascript

I have the following problem, lets say this is my html
<ul classname='products'>
<li classname='product'>
<div classname='product_title'>Product 1</div>
<div classname='product_thumbnail'><img src="product1.jpg"></div>
<div classname='product_images'>
<img src="product1_image1.jpg">
<img src="product1_image2.jpg">
</div>
</li>
<li classname='product'>
<div classname='product_title'>Product 2</div>
<div classname='product_thumbnail'><img src="product2.jpg"></div>
<div classname='product_images'>
<img src="product2_image1.jpg">
<img src="product2_image2.jpg">
</div>
</li>
<li classname='product'>
<div classname='product_title'>Product 3</div>
<div classname='product_thumbnail'><img src="product2.jpg"></div>
<div classname='product_images'>
<img src="product3_image1.jpg">
<img src="product3_image2.jpg">
</div>
</li>
</ul>
When I mouse over a product_image I want to change the product_thumbnail src to the product_image src. Its not very hard when I had one list item with the product_thumbnail having an ID
Then I could have done this
var $mainImage = $('#product_thumbnail'),
originalImageSrc = $mainImage.attr('src');
$('.product_images img')
.on('mouseover', function() {
var newImageSrc = $(this).attr('src');
$mainImage.attr('src', newImageSrc);
})
.on('mouseout', function() {
$mainImage.attr('src', originalImageSrc);
});
Working example: JSFiddle
Sadly enough I dont have one list item with an ID.
Of course when I try this code with classes and the html above it will always give me the src back of the first image in the first product_thumbnail div of the first list item.
I hope you guys understand my problem and someone can help me with the classes version of the jQuery example code.
Thanks in advance

First the html needs fixing - replace className with class. ClassName is the JavaScript attribute name for HTML class. For HTML jsut use class='foo'.
<ul class='products'>
<li class='product'>
<div class='product_title'>Product 1</div>
<div class='product_thumbnail'><img src="product1.jpg"/></div>
<div class='product_images'>
<img src="product1_image1.jpg">
<img src="product1_image2.jpg">
</div>
</li>
<li class='product'>
<div class='product_title'>Product 2</div>
<div class='product_thumbnail'><img src="product2.jpg"/></div>
<div class='product_images'>
<img src="product2_image1.jpg">
<img src="product2_image2.jpg">
<img src="product2_image3.jpg">
</div>
</li>
</ul>
And the JS now looks like this:
$('.product_images img')
.on('mouseover', function() {
var tgt = $(this).closest(".product").find(".product_thumbnail img")
tgt.data("orig_src", tgt.prop("src"))
tgt.prop("src", $(this).prop("src"));
})
.on('mouseout', function() {
var tgt = $(this).closest(".product").find(".product_thumbnail img")
tgt.prop("src", tgt.data("orig_src"));
});
The magic is in the selector. closest looks up the DOM from the starting element. We look for the closest element with class=product. When we find it we look for its child with class=product_thumbnail and then the child image of that. This all assumes there is only one occurrence, this code would be different if there were multiple hits.
Having found the target we first store its original src value in its data collection, then we replace the src value with the triggering img src.
On mouse out we take the src we stored in the thumbnails data and replace it.

Related

Add number to end of div with jQuery

I'm using jQuery to create a simple addClass on hover. Hovering over a #science-panel-number div triggers a class of .active to be added to an #iphone-screen-number div.
Here is my jQuery:
$('#science-panel-1').hover(function(){
$('#iphone-screen-1').addClass('active');
},function(){
$('#iphone-screen-1').removeClass('active');
});
$('#science-panel-2').hover(function(){
$('#iphone-screen-2').addClass('active');
},function(){
$('#iphone-screen-2').removeClass('active');
});
$('#science-panel-3').hover(function(){
$('#iphone-screen-3').addClass('active');
},function(){
$('#iphone-screen-3').removeClass('active');
});
My HTML:
<div class="col-md-4">
<div id="science-panel-1" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-2" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-3" class="science-panel__item">
Content goes in here!
</div>
</div>
<div class="col-md-4">
div id="iphone-screen-1" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
div id="iphone-screen-2" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-3" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-4" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-5" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-6" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
</div>
<div class="col-md-4">
<div id="science-panel-4" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-5" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-6" class="science-panel__item">
Content goes in here!
</div>
</div>
This feels like a lot of code to do the same script. Is there a way to have one piece of script that can add the numbers it self? As #science-panel-1 will always link to to #iphone-screen-1 and so on.
This will do what you need. Just apply the handlers to elements whose ID begins with science-panel-, which should cover all of them...
$("[id^=science-panel-]").hover(function() {
// get the corresponding iphone-screen element id
var iphoneScreen = "#" + this.id.replace("science-panel-", "iphone-screen-");
$(iphoneScreen).addClass("active");
},function() {
var iphoneScreen = "#" + this.id.replace("science-panel-", "iphone-screen-");
$(iphoneScreen).removeClass("active");
});
I recommend changing the markup to include the data you need to drive the script:
<div data-target="#iphone-screen-1" id="science-panel-1" class="science-panel__item">...</div>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This allows you to select all the science panel items at once:
$('.science-panel__item')
and perform the exact same script on each of them:
$('.science-panel__item').hover(function () {
$($(this).data('target')).addClass('active');
// ^^^^^^^^^^^^^^^^^^^^^^
// use the data-target attribute as a selector
}, function () {
$($(this).data('target')).removeClass('active');
});
If you change the attribute and the selector, you'll have a reusable feature you can apply to any element:
$('[data-hover-target]').hover(function () {
$($(this).data('hoverTarget')).addClass('active');
}, function () {
$($(this).data('hoverTarget')).removeClass('active');
});
I'd firstly ask if the active class is strictly necessary? Can what you want be achieved with CSS if it is for styling only by using the :hover pseudoclass?
If you do need the .active class for some reason, I would change the markup to be a little more generic so that all the science panels had a CSS class of .science-panel and all the iphone screens had a class of .iphone-screen. Then you could simplify the JS to look like
$('.science-panel').on('mouseenter mouseleave', function(e) {
$(this).find('.iphone-screen').toggleClass('active', e.type === 'mouseenter');
});
This will find the .iphone-screen inside of the .science-panel that you hover over and toggle the class to on if the mouse enters and off when the mouse leaves it.
edit: I see you've updated your answer to include your markup, this answer was assuming that your iphone-screens were nested in the science-panels so this won't necessarily work for you if you don't/can't nest your markup

Looping through ul li and using insertBefore to move image up two elements

I am learning js and jquery and have been trying to solve this litle issue I am having when trying to loop through a ul on the page and move a dom element specifically an image up two levels in my html. Here is what the html looks like:
<ul class="feedEkList">
<li class="slick-slide">
<div class="featured-title">
<div class="post-title">
some text
</div>
<div class="post-excerpt">
<img src="imageurl.jpg" class="wp-post-image">
<p>Post Description.</p>
</div>
</div>
</li>
</ul>
There are 10 li items in my ul but for readability purpose I only included one so you can see my html structure.
My javascript seems to be adding all the images before every featured-title div giving me piles of pictures instead of the one that is associated with that li.
$(function() {
$('.wp-post-image').insertBefore($('.featured-title'));
});
So then I tried this using each but it does not seem to do anything.
$(function() {
$('.feedEkList > li > .featured-title > .post-excerpt > .wp-post-image').each(function() {
$('.wp-post-image').insertBefore($('.featured-title'));
});
});
I was thinking maybe i need to use "this" in the code somewhere but I am new to javascript and not sure how to properly use "this" with the insert before, or if "this" is even the best option.
$('this.wp-post-image').insertBefore($('this.featured-title'));
Can anyone help me figure out what I am doing wrong? It is driving me nuts!
You need to iterate each image
For each image, get his parent .slick-slide.
Prepend the image to the .slick-slide using .prepend
Optional: If you need to insertBefore .featured-title see the comment.
$('.wp-post-image').each(function() {
var $this = $(this),
parentLi = $this.parents('.slick-slide').first();
$this.prependTo(parentLi);
//$this.insertBefore(parentLi.find('.featured-title'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="feedEkList">
<li class="slick-slide">
<div class="featured-title">
<div class="post-title">
some text
</div>
<div class="post-excerpt">
<img src="http://i.stack.imgur.com/FgiPG.jpg" class="wp-post-image" />
<p>Post Description.</p>
</div>
</div>
</li>
<li class="slick-slide">
<div class="featured-title">
<div class="post-title">
some text
</div>
<div class="post-excerpt">
<img src="http://i.stack.imgur.com/FgiPG.jpg" class="wp-post-image" />
<p>Post Description.</p>
</div>
</div>
</li>
<li class="slick-slide">
<div class="featured-title">
<div class="post-title">
removed the "wp-post-image" class to show how it was look before
</div>
<div class="post-excerpt">
<img src="http://i.stack.imgur.com/FgiPG.jpg" />
<p>Post Description.</p>
</div>
</div>
</li>
</ul>

Find closing anchor tag after image

I would like to move a div to the spot right after a closing anchor tag. All I have been given is the image classname. How do I find the closing anchor tag wrapping the image?
<img class="cat-image" src="http://placekitten.com/200/300" title="Funky roots" />
On JS Fiddle I have an example where I iterate through a list looking for an image with a certain class name. If that image exists I would like to move the '.moveMe' to after the closing anchor tag.
Unfortunately I can't modify the html. I can't add an id or class to the anchor or image tags or wrap the whole thing in a div.
HTML:
<ul class='testList'>
<li class="listItem-0">
<div class="moveMe"></div> <pre>
<div class="wrapper">
<img class="cat-image" src="http://placekitten.com/200/300" title="Funky roots" /><!-- moveMe div here -->
</div>
<div class="summary"></div>
</pre>
</li>
<li class="listItem-1">
<div class="moveMe"></div> <pre>
<div class="wrapper">
<div></div>
</div>
<div class="summary"></div>
</pre>
</li>
<li class="listItem-2">
<div class="moveMe"></div> <pre>
<div class="wrapper">
<img class="cat-image" src="http://placekitten.com/300/400" title="bigger cat pic" />
</div>
<div class="summary"></div>
</pre>
</li>
</ul>
JS:
var listItems = $(".testList li");
listItems.each(function (idx, li) {
if ($(li).find('.cat-image').length) {
console.log('listItemContent image==>', $('pre').find('.cat-image'));
/*$(li).find('???? </a> ????').append($(li).find('.moveMe'));*/
}
console.log($('.testList').html());
});
JS Fiddle
Try to use .after() in this context,
var listItems = $(".testList li");
var cache = null;
listItems.each(function (idx, li) {
cache = $(li).find('.cat-image');
if (cache.length) {
cache.parent().after($(li).find('.moveMe'));
}
});
DEMO
You can do this as follows:
var listItems = $(".testList li");
listItems.each(function (idx, li) {
var jli = $(li);
jli.find(".cat-image")
.closest("a")
.after(jli.find(".moveMe"));
});
which, if you like, can be reduced to a single line:
var listItems = $(".testList li");
listItems.each(function (idx, li) {
$(li).find(".cat-image").closest("a").after($(li).find(".moveMe"));
});
http://jsfiddle.net/MBTNU/5/

Switch Content of Div onclick

I've got two divs - each with one image inside. If I click on the image inside the second div I want this image to become the content of the first div (like a gallery).
It's important that I don't replace the links inside the img tag, so document.IMG1name.src=document.IMG2name.src isn't a possibility.
I tried it with innerhtml, but it doesnt work:
<div id="container1">
<img src="blablabla">
</div>
<div id="container2"; onclick="document.getElementById('container1').innerHTML=document.getElementById('container2').innerHTML"><img src="../funnycat.jpg">
</div>
mm... your code works fine, just close img tags and remove semicolon:
<div id="container1">
<img src="blablabla" />
</div>
<div id="container2" onclick="document.getElementById('container1').innerHTML=document.getElementById('container2').innerHTML"><img src="https://www.google.es/logos/doodles/2013/holiday-series-2013-3-4504416610680832-hp.jpg" />
</div>
here you have a demo: http://jsfiddle.net/HLs86/
HTML
<div class="pricing_table" id="monthly">
<ul>
<li>Basic</li>
<li>Subscribe Now</li>
</ul>
<ul style="background-color:#CCCCCC;">
<h2>Monthly Plans</h2><a class='plansSwitch' href='#yearly'>Click here to switch to the "Yearly Plans"</a></ul>
</div>
<div class="pricing_table" id="yearly">
<ul>
<li>Basic</li>
<li>Subscribe Now</li>
</ul>
<ul style="background-color:#CCCCCC;">
<h2>Yearly Plans</h2><a class='plansSwitch' href='#monthly'>Click here to switch to the "Monthly Plans"</a></ul>
</div>
JS
var $plansHolders = $('#monthly, #yearly').hide();
$('#monthly').show();
$('.plansSwitch').click(function() {
var href = $(this).attr('href');
$plansHolders.hide();
$(href).show();
});
you just need to add javascript: on your onclick action like this
<div id="container1"></div>
<div id="container2" onclick="javascript:document.getElementById('container1').innerHTML=document.getElementById('container2').innerHTML"><img src="http://i.imgur.com/0fS8dCsb.jpg"/>
</div>
there is example

Programmatically apply the image alt attribue as a class to parent element

I want to add as a class the image alt attribute to its container element. Markup:
<div class="field-group-our-people">
<div class="field-items even>
<img alt="John">
</div>
<div class="field-items odd>
<img alt="Kevin">
</div>
<div class="field-items even>
<img alt="Kate">
</div>
<div class="field-items odd>
<img alt="Martin">
</div>
</div>
To be like this:
<div class="field-group-our-people">
<div class="field-items even john>
<img alt="John">
</div>
<div class="field-items odd kevin>
<img alt="Kevin">
</div>
<div class="field-items even kate>
<img alt="Kate">
</div>
<div class="field-items odd martin>
<img alt="Martin">
</div>
</div>
My Jquery code(but not working):
//Add the image alt attribute as class for individual styling
$('.group_our_people .field-item').each(function() {
var att = $('.group_our_people .field-item img').attr('alt');
$(this).addClass(att);
});
What is wrong/missing in my code?
You should get the img that is child of the current div (on iteration):
var att = $(this).find('img').attr('alt');
The way you're doing (i.e. repeating the selector), you end up retrieving multiple values, and only the first one is taken into account. So, every div will get its class: "John".
$('.field-group-our-people .field-items img').each(function() {
$(this).parent().addClass( $(this).attr('alt') );
});
$('div.field-group_our_people div[class^=".field-items"] img').each(function()
{
var att = $(this).attr('alt');
$(this).parent().addClass(att);
});

Categories