Animate img replacement on jquery hover - javascript

I am trying to replace some logo images on a web site with a all white version of the same image. The idea is that when you hover over the image you see the logo in white with a coloured background (done in css)
jQuery(document).ready(function() {
jQuery('.la-item img').hover(function() {
var image = jQuery(this).attr('data-imagenormal')+'-white.png';
jQuery(this).attr("src", image)
jQuery(this).addClass("circleitem")
}, function() {
var image = jQuery(this).attr('data-imagenormal')+'.png';
jQuery(this).attr("src", image )
jQuery(this).removeClass("circleitem")
});
});
This actually looks great, but I would like it to animate the change over 2 seconds. I've tried using this.animate, but it does not work.
jQuery(document).ready(function() {
jQuery('.la-item img').hover(function() {
var image = jQuery(this).attr('data-imagenormal')+'-white.png';
jQuery(this).animate({
jQuery(this).attr("src", image)
jQuery(this).addClass("circleitem")
)}
}, function() {
var color = jQuery(this).attr('data-imagenormal')+'.png';
jQuery(this).animate({
jQuery(this).attr("src", color )
jQuery(this).removeClass("circleitem")
});
})
});

Don't use <img> tag, just use CSS and backgrounds.
For example (I'm not trying to have the same structure than yours) :
HTML
<div id="logo"></div>
CSS
#logo {
width: 50px;
height: 50px;
background-color: #whatyouwhant;
background-image: url('yourlogo.png');
background-position: center center;
background-repeat: no-repeat;
transition: .3s;
}
#logo:hover {
background-image: url('yourwhitelogo.png');
}
You can combine background colors and transparent PNGs.
You can use this technique and still change the background with jQuery :
$('.matchyourelements').hover(function() {
$(this).css('background-image', $(this).data('imagenormal')+'-white.png');
});

you can do something like this.
<img src="one.png" id="one" />
//Script
$('#one').hover(function() {
// increase the 500 to larger values to lengthen the duration of the fadeout
// and/or fadein
$('#one').fadeOut(500, function() {
$('#one').attr("src","/newImage.png");
//here you can add or remove class
$('#one').fadeIn(500);
});
});

Related

Image Carousel with Fade to Black Transition

I need to make a carousel with a fade transition that goes black, or even better some dark grey color like #2B303A. I've found this code on the web that works perfectly, the only problem is that the fade effect is a really bright white that I don't like and it's bothering for the eyes.
How can I make it fade to black between images?
$(document).ready(function() {
//Carousel
var vet_url = ["https://i.imgur.com/Bb39Qpp.jpg", "https://images.wallpaperscraft.com/image/palms_road_marking_123929_1920x1080.jpg"];
var len = vet_url.length;
var i = 0;
function swapBackgrounds() {
$("#background").animate({
opacity: 0
}, 700, function() {
$($("#background")).css('background-image', 'url(' + vet_url[(i + 1) % len] + ')').animate({
opacity: 1
}, 700);
});
i++;
}
setInterval(swapBackgrounds, 10000);
});
#background {
background-color: #2B303A;
position: absolute;
z-index: 1;
min-height: 100%;
min-width: 100%;
background-image: url("https://images.wallpaperscraft.com/image/palms_road_marking_123929_1920x1080.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="background"></div>
View on JSFiddle
you need to do it on the html element, in your test case at least.
html
{
background-color:#2B303A;
}
Setting the opacity to 0 let you see the element underneath the carousel, in this case there's nothing but the body itself. The background-color of the body wasn't set so it was the default white one. Setting the background-color to black solved the problem.
jquery's .animate does not work with background-colors though it can work with:
https://github.com/jquery/jquery-color

Force a background image to be loaded before other background images

Is there a way to force downloading a specific image (priority image) before other images are downloaded?
I use many background images. My landing page has a gradient fill used as my second image of my landing page.
landing page CSS:
.bg-img1::before {
background-image: url(https://mywebsite/images/myimage.jpg), linear-gradient(to top, #206020, white);
background-size: cover, cover;
}
I switched from using DOM ready detection as my background image gradient was displaying 3 or 4 seconds before my landing page image was downloaded...
$(function() {
// DOM ready, but image hasn't downloaded yet.
});
Now I use window.onload and everything is working fine, but I am adding more and more images and the downloading delay is becoming substantial.
window.onload = function() {
// delay, delay... finally my landing page with gradient displays
});
To reiterate my question, I would like to be able to make downloading my landing page a priority. Is there a way to ensure that my background image displays before my gradient is displayed if I switch back to using DOM ready?
add an image tag and place the source in it. make sure that you add display none to this tag. place this tag as high up in your body tag. this should prioritize your image loading. hope this works for you.
Maybe the script I did for you works as you expect. By using JS there's no possibility to set the CSS pseudo elements such the :before.
What I did, was to change the code so it provides the img URL as data attribute in the image containers.
Then using the JavaScript I hide all the image containers and start creating new images dynamically, and then I set the src attribute, to the value of the data-img of the section element.
Finally, I listen for the load and error event, and then I show again the container. This way you can be sure, that the image it is already loaded in the browser, and thus when the image container it is displayed will have the image already in place.
(
function ( $, window, undefined ) {
var img_container = null;
var img_loaded = 0;
var hide_img_containers = function hide_img_containers() {
if ( 0 < img_container.length ) {
img_container.hide();
}
}
var show_img_containers = function show_img_containers( $element ) {
$element.show();
}
var load_images = function () {
img_container.each(
function() {
var $section = $( this );
var $img = $section.attr( 'data-img' );
var img = document.createElement('img');
img.src = $img;
img.addEventListener(
'load',
function () {
show_img_containers ( $section );
}
);
img.addEventListener(
'error',
function () {
show_img_containers ( $section );
}
);
}
);
}
$( document ).ready(
function ( $ ) {
img_container = $( '.img_container' );
hide_img_containers ();
load_images();
}
);
}
)( jQuery, this );
.img_container {
min-height: 250px;
position: relative;
}
.img_container:before {
content: '';
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
position: absolute;
}
#sec_1:before {
background-image: url(http://www.lifeofpix.com/wp-content/uploads/2017/03/dscf0786.jpg), linear-gradient(to top, #206020, #fff);
background-size: cover, cover;
}
#sec_2:before {
background-image: url(http://www.lifeofpix.com/wp-content/uploads/2017/03/dscf0357.jpg), linear-gradient(to top, #206020, #fff);
background-size: cover, cover;
}
#sec_3:before {
background-image: url(http://www.lifeofpix.com/wp-content/uploads/2016/05/Life-of-Pix-free-stock-street-lights-wall-PaulJarvis.jpg), linear-gradient(to top, #206020, #fff);
background-size: cover, cover;
}
#sec_4:before {
background-image: url(http://www.lifeofpix.com/wp-content/uploads/2017/03/1-276.jpg), linear-gradient(to top, #206020, #fff);
background-size: cover, cover;
background-position: 50% 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="sec_1" class="img_container" data-img="http://www.lifeofpix.com/wp-content/uploads/2017/03/dscf0786.jpg"></section>
<section id="sec_2" class="img_container" data-img="http://www.lifeofpix.com/wp-content/uploads/2017/03/dscf0357.jpg"></section>
<section id="sec_3" class="img_container" data-img="http://www.lifeofpix.com/wp-content/uploads/2016/05/Life-of-Pix-free-stock-street-lights-wall-PaulJarvis.jpg"></section>
<section id="sec_4" class="img_container" data-img="http://www.lifeofpix.com/wp-content/uploads/2017/03/1-276.jpg"></section>

CSS Background image, fade once loaded

I want to fade-in the "image" once it is loaded from an external url, but show a "imgPlaceholder" right from the beginning from local resources.
The HTML looks like this:
<div className="bg-img" style={imgDivStyle}></div>
The CSS looks like this:
const imgDivStyle = {
background: `url('${image}'), url('${imgPlaceholder}')`,
backgroundSize: 'cover',
};
What I want to happen: Show "imgPlaceholder" from beginning and Fade-in "image" once it is loaded.
What is actually happening: "imgPlaceholder" is shown from beginning "image" is showing up instantly once it is loaded.
Is this achievable by pure CSS? Or do I need to load in the image using e.g. jQuery and trigger an animation manually?
You can't check if the image has loaded with css alone so you could do something like the following (comments in code to show what is happening):
$('.inner').each(function() {
var div = $(this),
background = div.data('background'); // get background
$('<img/>').attr('src', background).load(function() { // create an image element with inner background and load it
$(this).remove(); // remove it
// set the inner background image and fade in:
div.css('background-image', 'url(' + background + ')').delay(200).fadeIn(2000); // need a little delay to let the div render it's bg image before the fade starts
});
});
.default,
.inner {
background-size: cover;
background-repeat: no-repeat;
background-position: center;
/* just make sure inner div is same size as outer */
width: 400px;
height: 400px;
}
.default {
background-image: url(https://lorempixel.com/900/900/city/1/); /* default background */
}
.inner {
display:none; /* start of hidden */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="default"><!-- default div with default background image -->
<div class="inner" data-background="https://lorempixel.com/900/900/city/2/"><!-- inner div with background-image set as data attribute -->
</div>
</div>
If you want to create the inner div on the fly, you can do something like this:
$('.background').each(function() {
var div = $(this),
background = div.data('background'), // get background
html = div.html(); // get any contents
$('<img/>').attr('src', background).load(function() { // create an image element with inner background and load it
$(this).remove(); // remove it
div.empty(); // empty current div
// create an inner div:
$('<div/>')
.css({
'background-image': 'url(' + background + ')',
'display': 'none'
}) // add background and hide
.addClass('inner')
.html(html)
.appendTo(div) // append to default div
.delay(175)
.fadeIn(2000); // need a little delay to let the div render it's bg image before the fade starts
});
});
.background,
.inner {
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
.background {
background-image: url(https://lorempixel.com/900/900/city/1/); /* default background */
/* just make sure inner div is same size as outer */
width: 400px;
height: 400px;
}
.inner {width:100%; height:100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="background" data-background="https://lorempixel.com/900/900/city/2/"><!-- default div with default background image, new background image set as data attribute -->
</div>
I found a reference that utilizes #keyframes along with some attributes like 'opacity' within an animation frame.
You can try referencing some of the code in the link here -
https://codepen.io/davidhc/pen/nLpJk
#keyframes fade
{
0% {opacity:1}
33.333% { opacity: 0}
66.666% { opacity: 0}
100% { opacity: 1}
}

How to add a diffrent background image to different div elements on hover?

I have several div elements aligned in a grid. I want them to have their specific different background images when the user hovers over them which disappear when the mouse leaves the div. Basically it's a users information page where every square has the data of a user. When people hover over the squares, the users' images appear as background images. Here's the HTML:
<div class="contributor">
Some great stuff here
</div>
Here's the jQuery code I'm currently using. The problem: It assigns the same image to every div while I want different images for each div.
$(document).ready(function(){
$('.contributor').mouseenter(function(){
$(this).addClass('visible');
});
$('.contributor').mouseleave(function(){
$(this).removeClass('visible');
});
});
Here's the code for the 'visible' class:
.visible{
background-image: url('../res/dev-1.png');
}
Why do you use jQuery? use just CSS and pseudo-class :hover.
.contributor:hover{
background-image: url('../res/dev-1.png');
}
apply for diffrent div:
.contributor.diff-div:hover{
background-image: url('../res/dev-2.png');
}
If you can do something in the CSS, it is almost always it will be a better solution than using JavaScript
First, save the image url in an attribute named "imageurl" (which isn't parsed by the browser):
<div class="contributor" imgageurl="../res/dev-1.png"></div>
<div class="contributor" imgageurl="../res/dev-2.png"></div>
Then, use this jQuery code:
$('.contributor').mouseenter(function(){
var imgageUrl = $(this).attr("imageurl");
$(this).css("background-image" , imgageUrl);
});
$('.contributor').mouseleave(function(){
$(this).css("background-image" , "none");
});
Of course, you also have to build the HTML dynamically.
may be you can consider css function instead of addClass.
$(document).ready(function(){
$('.contributor').mouseenter(function(){
if(this.id == "one")
$(this).css("background-image" , "url('../res/dev-1.png')");
else if(this.id == "two")
$(this).css("background-image" , "url('../res/dev-2.png')");
});
$('.contributor').mouseleave(function(){
$(this).css("background-image" , "none");
});
});
Try this with jquery. suppose you have six images from dev-1.png to dev-6.png then it will set them as bacground for div number 1 to 6 respectively
$(document).ready(function(){
$('.contributor').mouseover(function(){
var index = $("div").index(this);
index++;
var bI= "background-image:url('../res/dev-"+index+".png');";
$("this").eq(index).attr('style',bI);
});
$('.contributor').mouseleave(function(){
var index = $("div").index(this);
index++;
var bI= "background-image:none";
$("this").eq(index).attr('style',bI);
});
});
For reference (Too troublesome and Won't apply if you have a ton of elements)
This can be achieved with pure CSS.
images might take a second to load (random image services)
Working example: (not responsive open in full page)
.optionlist li {
background: #111;
color: #999;
padding: .5em;
list-style-type: none;
border: 1px solid;
max-width: 70px
}
.optionlist li:hover {
background: red;
}
.optionlist li:hover:after {
content: '';
width: 800px;
height: 600px;
position: fixed;
top: 30%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Start Background Control */
#red:after {
background: url(http://lorempixel.com/800/600/)
}
#blue:after {
background: url(http://lorempixel.com/800/601/)
}
#green:after {
background: url(http://lorempixel.com/801/600/)
}
#yellow:after {
background: url(http://lorempixel.com/801/601/)
}
#orange:after {
background: url(http://lorempixel.com/799/600/)
}
#white:after {
background: url(http://lorempixel.com/800/599/)
}
#black:after {
background: url(http://lorempixel.com/801/599/)
}
/* End Background Control */
<div class="optionlist">
<ul>
<li id="red">Red</li>
<li id="blue">Blue</li>
<li id="green">Green</li>
<li id="yellow">Yellow</li>
<li id="orange">Orange</li>
<li id="white">White</li>
<li id="black">Black</li>
</ul>
</div>

Can I slow down this Javascript function?

I'm new to javascript and jquery, so please forgive my ignorance. I created a webpage where you rollover a text link and an image in another div changes. I used the method from here: http://jsfiddle.net/fWpJz/1/ to create my page and it works well.
Here is the code I'm using:
$(document).ready(function () {
$('.productmenu a').hover(function () {
$('#prodimage img').attr('src', $(this).data('image-src'));
$('.image-src').stop().animate({.attr}, slow);
});
});
I'd like to slow down the transition from one image to another on mouse over, so that the image doesn't flip as abruptly.
I used this tutorial (http://bavotasan.com/2009/creating-a-jquery-mouseover-fade-effect/) to create an effect that I like, but don't know how to combine it with the image changes based on a link hover. Here is the code from the jsfiddle.net:
$(document).ready(function () {
$('.menu a').hover(function () {
$('#container img').attr('src', $(this).data('image-src'));
});
});
Can anyone point me to the correct piece of code and how I can add it into my javascript? I've never used jquery before, so I don't know how to add an animate function.
Thank you!!
What if I told you you didn't have to use jQuery.animate at all to achieve the effect you want? Use CSS3 transitions! Here's a forked version of your fiddle showing how to accomplish what you're looking to do (I think) (I've put the html/css/js at the bottom of this post as well).
When the DOM content has loaded, the alignItems function makes sure that all images stay in the same place on the page. The script keeps track of the current image being displayed. Every time a different link is moused over, the image being displayed gets updated, such that the old current image gets its opacity set to 0 and the new current image gets its opacity set to 1. Then CSS transitions can be used to animate the opacity, which blows away $.fn.animate, but will only work on modern browsers (see caniuse...motherf***ing IE -_- ). Code below:
html
<div class="menu">
link 1
link 2
link 3
link 4
link 5
</div>
<div id="container">
<img id="1" src="http://farm7.staticflickr.com/6092/6330704947_dd7e1b453c_t.jpg" />
<img id="2" src="http://farm1.staticflickr.com/13/15463218_8651d51b21_t.jpg"/>
<img id="3" src="http://farm3.staticflickr.com/2570/4220856234_029e5b8348_t.jpg" />
<img id="4" src="http://farm4.staticflickr.com/3036/2975303180_86c4858b2b_t.jpg" />
<img id="5" src="http://farm7.staticflickr.com/6216/6240217938_aeed84634a_t.jpg" />
</div>
css
.menu a {
padding: 2px 4px;
color: #555;
text-decoration: none;
}
.menu a:hover {
color: #ddd;
background: #333;
}
#container {
margin-top: 10px;
}
#container img {
margin: 4px;
padding: 4px;
border: 1px dashed #aaa;
opacity: 0;
-webkit-transition: opacity 500ms ease-in;
-moz-transition: opacity 500ms ease-in;
transition: opacity 500ms ease-in;
}
javascript
$(document).ready(function () {
alignImages();
var currentImgId = 0;
$('.menu a').hover(function () {
var oldImgId = currentImgId;
currentImgId = this.dataset.imageId;
$(document.getElementById(oldImgId)).css('opacity', 0);
$(document.getElementById(currentImgId)).css('opacity', 1.0);
});
});
function alignImages() {
var $images = $('#container img');
var position = $images.eq(0).position();
$images.each(function() {
this.style.position = 'absolute';
this.left = position.left;
this.top = position.top;
});
}
Below is one of the implementations by using setTimeout
var count = 0;
$(document).ready(function () {
$('.menu a').hover(function () {
var self = this;
var innerCount = ++count;
setTimeout(function(){
if(innerCount == count) //If mouse move out within 1 second, will not show new image
{
$('#container img').attr('src', $(self).data('image-src'));
}
}, 1000); //1 second delay
});
});
Try this:
your HTML should be like this:
<div id="container" style="display:none;">
<img src="">
</div>
and in your script :
$('.menu a').hover(function () {
$('#container').hide();
$('#container').fadeIn().animate({ opacity: 1, top: "-10px" }, 'slow');
$('#container img').attr('src', $(this).data('image-src'));
});
Effect should be nice in transition See: JSFiddle

Categories

Resources