Mouseover image stays the same - javascript

I have a problem with this code
I'll explain a little how this works,
The idea of this is that when hovering in tag (a), change the image of the id="meal", by the one that is in the (data-meal = "meal-14") .. in a few words
The pre-determined image is meal-0.png, hover in tag (a) with (data-meal = 14), replaces the url of the image with (meal-14.png),
Everything works fine, I only have one problem and is that when you stop hovering, do not go back to the pre-determined image, it stays in the image that became hover. Should return to the image meal-0.png.
<div class="imagen-hover" id="meal">
<img src="/public/tienda/meal-0.png" alt="">
</div>
<ul>
<li><a class="carne-a" data-meal="meal-14">14. Punta de Anca</a></li>
<li><a class="carne-a" data-meal="meal-16">16. Chata Angosta</a></li>
</ul>
jQuery(document).ready(function($) {
var path = "/public/images/";
$(".meal-a").on("mouseover", function() {
var meal = $(this).attr("data-meal") + ".png";
$("#meal img").attr("src", path + meal)
});
});

that is because it is doing exactly what you told it to do.
you need to make another event handler for mouseleave
or you can look at the jQuery docs , mouseenter can take two call backs , one for entering and one for leaving
$(".meal-a").mouseenter( function() {
var meal = $(this).attr("data-meal") + ".png";
$("#meal img").attr("src", path + meal)
}).mouseleave( function() { //for when mouse leaves
});
What I would recommend though... you do not need javascript or jQuery at all for this , there is a css selector for while the user is hovering over an element
.meal-a{ // regular code
}
.meal-a:hover{ // hover code
}

Also add a "mouseout" function to handle returning the image to its previous value
$(".meal-a").on("mouseout", function() {
$("#meal img").attr("src", "meal-0.png")
});

Related

Show a different image (bigger version) on mouse hover

I want to load a different image (A bigger version) of existing one when mouse is hovered over that image. So I place all the images through AJAX call
<main class="container">
<ul class="gallery">
</ul>
</main>
success: function (data) {
$.each(data, function (index, element) {
$(".gallery").append($(`<img src="${`images/square/${element.path}`}"
alt="${element.title}"id="${element.path}"city="${element.city}"
taken="${element.taken}"/>`));
});
},
Now I want to load a bigger image (from local disk) of existing image when mouse is hovered and show that image over it (kind of zoom in, but not zoom in over the image but load a bigger image, and append the div to body) in the body.
I've tried many different versions of this
(".gallery").mouseenter(function(){
$(this).css("gray");
$(this).append('<div id="preview"');
// console.log($(this).attributes);
// $(this).append($(`<img src="${`images/medium/"${$(this).attr('id')}"`}"
// alt="${$(this).attr('title')}"/>`
// ));
$(this).append('</div>')
})
I am unable to access the attributes dynamically. this. attribute remains return undefined. Something seems off here. Can you please tell, how to go about it ?
You are getting attribute of .gallery which doesn't have any id or alt your img tag has that so use .find() to get that particular image where user hover and then get attributes using .attr('yourattributename').
Demo Code :
$(document).on('mouseenter', '.gallery li', function() {
var imgs = "<div id=preview><img src=images/medium/" + $(this).find('img').attr('id') + " alt=" + $(this).find('img').attr('alt') + "></div>";
$(this).append(imgs)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="container">
<ul class="gallery">
<li><img src="images/square/${element.path}" alt="Soemehing" id="Soemehingdd" city="${element.city}" taken="${element.taken}" />
</li>
<li><img src="images/square/${element.path}" alt="Soemehing2" id="Soemehingdd2" city="${element.city}" taken="${element.taken}" />
</li>
</ul>
</main>
Use arrow function instead of normal fucntion.
Arrow functions do not bind their own this, instead, they inherit the one from the parent scope, which is called "lexical scoping".
(".gallery").mouseenter(() => {
$(this).css("gray");
$(this).append('<div id="preview"');
// console.log($(this).attributes);
// $(this).append($(`<img src="${`images/medium/"${$(this).attr('id')}"`}"
// alt="${$(this).attr('title')}"/>`
// ));
$(this).append('</div>')
})

jQuery Lightbox gallery only working once

I am trying to build my own simple jQuery lightbox gallery. My logic behind it is as follows: Only thumbnails will be shown & created at first. These link to the full size images.
<section class="gallery-set">
<a href="img/about/gallery/a1.1.jpg">
<img src="img/about/gallery/thumb1.1.jpg" alt=""
height="192" width="383">
</a>
<a href="img/about/gallery/a1.jpg">
<img src="img/about/gallery/thumb1.jpg" alt=""
height="192" width="383">
</a>
<a href="img/about/gallery/a2.1.jpg">
<img src="img/about/gallery/thumb2.1.jpg" alt=""
height="192" width="383">
</a>
</section>
Therefore, when you click on any of these thumbnails, I dynamically create an overlay-lightbox and all full size images, showing only the one that links to the thumbnail you clicked. Although the rest of the images has been created too, these are hidden for now.
function lightBox() {
var gallery = $('.gallery-set'),
overlay = $('<div/>', {id: 'overlay'});
overlay.appendTo('body').hide();
gallery.on('click', 'a', function(event) {
event.preventDefault();
var clickedThumb = $(this),
clickedThumbPath = $(this).attr('href'),
clickedImg = $('<img>', {src: clickedThumbPath, alt: 'fullSizeImage', class: 'current'}),
prevThumbs = clickedThumb.prevAll(),
nextThumbs = clickedThumb.nextAll();
prevThumbs.each(function() {
var prevImg = $('<img>', {src: $(this).attr('href'), class: 'prev non-current'});
prevImg.appendTo(overlay);
});
clickedImg.appendTo(overlay);
nextThumbs.each(function() {
var nextImg = $('<img>', {src: $(this).attr('href'), class: 'next non-current'});
nextImg.appendTo(overlay);
});
overlay.show();
})
.....
.....
}
Now, when you click the second thumbnail, jQuery dynamically creates all the fullsize images and this is how HTML structure looks like:
Now that I have this structure, I can easily traverse the full sized images by left and right arrows. The current image gets hidden and the next one gets shown. For this logic I am using two classes, current and non-current where the first one has set display to block and the second one to none. This piece of code is within the lightbox() function:
$(document).on('keyup', function(event) {
var pressed = event.keyCode || event.which,
arrow = {left: 37, right: 39};
switch(pressed) {
case arrow.left:
var curr = overlay.find('.current'),
prev = curr.prev();
if(curr.hasClass('current')) {
curr.removeClass('current').addClass('non-current');
} else {
curr.addClass('non-current');
}
if(prev.hasClass('non-current')) {
prev.removeClass('non-current').addClass('current');
} else {
prev.addClass('current');
}
break;
case arrow.right:
var curr = overlay.find('.current'),
next = curr.next();
curr.removeClass('current').addClass('non-current');
next.removeClass('non-current').addClass('current');
break;
}
});
overlay.on('click', function() {
overlay.hide();
overlay.find('img').remove();
});
});
Everything works fine the first time. However, once I close the lightbox and try to open it again, the correct image opens but the arrows functionality is gone. I do not understand why - since I am dynamically creating the full sized images everytime user clicks on the gallery and putting event listeners (arrows) only once these have been created.
Just for the record, I am calling this lightbox() function from the HTML file right before the closing tag.
Any ideas much appreciated. Also, if there's a simpler / better way of doing this, please do let me know! I don't want to use any plugin as I think this is pretty simple and straightforward. Or, I thought it WOULD BE SIMPLE I should rather say.

Revert to original image after jquery hover better way?

to replace images on hover i have used jquery:
<script type='text/javascript'>
$(document).ready(function(){
var blog1 = $(".blogimage1").attr('src');
$(".imghover").hover(function() {
$(this).attr("src","images/imghover.png");
}, function() {
$(this).attr("src",blog1);
});
});
</script>
here is the html:
<a href="blog-inner.html" title="read more">
<img src="images/blogpost4.jpg" alt="blog post title" class="img-responsive imghover blogimage1">
</a>
and it works exactly like i want it to, however i dont know how many blog images there will be so for now i would have to add in blogimage1, blogImage2, etc into the html and do the same with jquery. is there a way i can do this without having to store each original blog image and write the same function a million times?
Try this : You can save previous image in blog1 variable when mouse hover and replace it back when mouse leave.
$(document).ready(function(){
var blog1 = '';
$(".imghover").hover(function() {
//save previous image in variable
blog1 = $(this).attr('src');
$(this).attr("src","images/imghover.png");
}, function() {
$(this).attr("src",blog1);
});
});
Use .data() to store original image path.
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
code
$(".imghover").hover(function() {
$(this).data('orgimage', this.src); //Store data
this.src = "images/imghover.png";
}, function() {
this.src = $(this).data('orgimage'); //Retrieve and set original image path
});

Toggling Background Color on Click with Javascript

I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.

Hover on images to show larger hidden image linked by alt tag?

please see this fiddle http://jsfiddle.net/rabelais/fEaAZ/4/
How can I link the small thumbnail image to the larger hidden image by using the alt tag of the images?
I want the matching hidden image to show on hover of the smaller thumbnails.
$(".thumbnails").on("mouseover mouseout", "img", function () {
var flag = $(this).data('flag');
$('[alt="' + $(this).attr('alt') + '"]').css('visibility', flag ? 'hidden' : 'visible');
$(this).data('flag', !flag);
});
If I understand you correctly, then your biggest problem is that previously displayed images are not hidden when other picture needs to be displayed.
When you hover over thumbnail with alt set to 'alicecurls', you are changing visibility of both thumbnail and big picture, but only of those which contain that exact alt. This means that picture previously visible stays visible.
You might want to go through all the big pictures and hide the ones which don't have the right value of attribute alt.
I would change your code in the following way:
$(".thumbnails").on("mouseover mouseout", 'img', function () {
var alt = $(this).attr('alt');
$('.displayed-image > img').each(function(index, element) {
var el = $(element),
visibility = el.attr('alt') === alt ? 'visible' : 'hidden';
el.css('visibility', visibility);
});
});
Here is the fiddle with changed code: http://jsfiddle.net/mj7ba/.
However, you need to define which picture should be displayed after the user moves its mouse away from the picture.
I would suggest the following changes:
not to abuse alt attribute and use data-* for this purpose
using id in the selectors
using displayed-image as a placeholder, because original image already contains correct url
Here is the code: fiddle
Javascript:
$(".thumbnails").on("mouseover ", "img", function () {
$('#' + $(this).attr('data-large'))
.attr('src', $(this).attr('src'))
.css('visibility', 'visible');
});
$(".thumbnails").on("mouseout ", "img", function () {
$('#' + $(this).attr('data-large')).css('visibility', 'hidden');
});
Html:
<div class="thumbnails">
<img src="http://intelligen.info/images/Personal/instagram Randoms/alicecurls.jpg" data-large="alicecurls"/>
<img src="http://intelligen.info/images/Personal/instagram Randoms/genna.jpg" data-large="genna"/>
</div>
<div class="displayed-image">
<img id="alicecurls" class="repeatable" />
<img id="genna" class="repeatable" />
</div>

Categories

Resources