change background image in no time - javascript

I am changing background image of a div on event basis,
There are two image
Image1
and
Image2
I have to use these two images on condition basis, it is working fine, but at first time when i change image, it takes time to load, how to load it instantly
div has image1 as default background image,
and I am changing it with below code
$("div").addClass('loadalternateImage');
alternate image is class with background-image with image2
but it take time to load Image2.
Please advise how to load it instantly
Thanks

You can preload both images in a div outside the viewport. So, when you click in order to change background, both images should have been loaded.
HTML:
<div class="img-container">
<img src="first/img" />
<img src="second/img" />
</div>
CSS:
.img-container {
position: fixed;
top: -100000px;
}
You can also bind the click event after page loads (not on document ready) in order for the images to get fully loaded:
$(window).load(function() {
$(document).on('click', '#your-div', function() {
// change background
});
});

Option 1
I suggest you to have a look at this post
Therefore, you could use the base64 encoding for your image and put it directly to your stylesheet:
loadalternateImage {
background: url(data:image/gif;base64,....) no-repeat left center;
}
Option 2
Alternatively, you could put this your into some invisible node, which would also trigger the preloading:
<img src="original.jpg">
<img src="secondary.jpg" style="display:none;">
Option 3
Use sprites - have a look at this post. It is the most difficult solution from the maintenance point of view

Ok retain the answer by #kapantzak but do this
Switch between
$("#imgBackground')[0].src = $("#firstImg")[0].src
and
$("#imgBackground')[0].src = $("#secondImg")[0].src
imgBackground is the id of IMG tag as your background.
//Code block from #kapantzak
$(window).load(function() {
$(document).on('click', '#your-div', function() {
// put the code above here..
});
});

Related

How to make an element appear then disappear on click

I have been trying to make a random image appear on click by adding a fadeOut effect and then removing the class. when I click it works fine, but I don't know how to remove the class after a few milliseconds and then being able to appear again on another click. so far I have just been able to make it fade out on click, I have tried a setInterval function so that the class gets removed after 1 millisecond but didn't work so I erased it, but even then, I don't know how to make the .on('click', function()) function fire on every click, instead of just working once. any help or tips would be really appreciated. Thanks!
<style>
body {
background-color: black;
}
img {
opacity: 0;
width: 40px;
z-index: 0;
position: relative;
top: 3em;
}
</style>
<img class="red"
src="http://www.clker.com/cliparts/0/f/1/f/130267960774173786paint-
splash(red)-md.png" alt="">
<img class="blue" src="http://www.clker.com/cliparts/Q/3/H/u/Z/K/dark-blue-
splash-ink-hi.png" alt="">
<img class="yellow" src="http://www.clker.com/cliparts/3/y/m/m/p/P/yellow-
splash-ink-md.png" alt="">
<script>
$(document).ready(function(){
var red = $(".red");
var blue = $(".blue");
var yellow = $(".yellow");
var images = [red, blue, yellow];
$(document).on('click', function(){
$(images[(Math.floor(Math.random()*3))]).addClass("animated fadeOut");
});
})
//i should be able to click anywhere on the screen and a random image should appear and then fadeout each time there is a click
</script>
Try something like this:
$(document).on("click", function() {
$("#element").show(0, function() {
$("#element").fadeOut();
});
});
$("#element").hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="element">Element</span>
It looks like you are using jQuery so you simply need to:
1) Create a function that hides the class. Example:
function hideStuff(){
$(".myimg").hide();
}
2) Add a class to your image files so they have a common selector (like "myimg" below). You may also want to add an "alt" attribute (was missing in your code). Example:
<img class="yellow myimg" src="http://www.clker.com/stuff" alt="image-three">
3) Add the timeout as part of your function with the amount of delay you want. While it is not required, you should include a variable name so you can call it in the future. Example:
var myTimeout = setTimeout( hideStuff, 5000);
Hopefully these will get you going in the right direction.
Both .fadeOut() and .hide() set display: none, which could effect your layout. I think you're looking to animate opacity to 0, and then in the callback function you can change the image source. I'd recommend using a div and setting the background-image property since divs are a bit more layout friendly. Also, you could either use classes and set the background-image property in the <style> section or you can make an array of the image urls and randomly pick from that (which is what I did here).
let images = [
'http://www.clker.com/cliparts/0/f/1/f/130267960774173786paint-splash(red)-md.png',
'http://www.clker.com/cliparts/Q/3/H/u/Z/K/dark-blue-splash-ink-hi.png',
'http://www.clker.com/cliparts/3/y/m/m/p/P/yellow-splash-ink-md.png'
];
$(document).on('click', function() {
let $img = $('.img'); //so you don't have to make a new object everytime it's used
if ($img.css('opacity') === '1') {
$img.animate({ opacity: 0 }, function() {
$img.css('background-image', `url(${images[Math.floor(Math.random()*3)]})`);
});
} else {
$img.animate({ opacity: 1 });
}
}).click().click(); //two clicks to initialize image
https://jsfiddle.net/yc4e4nxb/3/
NOTE: JSfiddle doesn't seem to like wherever these images are hosted, so it's working kind of erratically. Hopefully you get the gist of what this code is doing though.
http://api.jquery.com/animate/
If I understood the question correct, In This Fiddle the button element disappears when you click anywhere in the screen and then re appears immediately. Hope this will work.
$(document).ready(function(){
$(document).on('click',function(){
$("#myElement").fadeOut().delay(100).fadeIn();
});
});

jQuery Image Swap Not Showing Immediately

I'm using the jQuery code below to replace part of the image src. Basically it converts example.com/200x200/sample.jpg into example.com/500x500/sample.jpg.
It works fine only problem is it renders the old image first before showing the new one. Is it possible to load the swapped image first to improve user experience?
$(document).ready(function() {
$(".gallery img").each(function() {
$(this).attr("src", function(a, b) {
return b.replace("200x200", "500x500")
})
})
});
JSFiddle Demo
(Click "Run" multiple times)
Put the image in fixed position div that has overflow hidden and height and width of 0. This will cause the image to load but not display. Here is a fiddle showing the basic idea: https://jsfiddle.net/0tm3kb6e/. This image displays after 10 seconds. Use chrome to throttle the network and you will see that it is loaded by the time it is displayed. Here is the code I used. You just need the html and css
html
<div id="image-hider">
<img src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
css
#image-hider {
height:0;
width: 0;
overflow: hidden;
position: fixed;
}
javascript
$(document).ready(function() {
setTimeout(function() {
$('#image-hider').css('height','500px');
$('#image-hider').css('width','500px');
}, 10000);
});
Try using a overlay div
<div class="gallery">
<img src="//lorempixel.com/200/200" />
<div class="overlaydiv"> </div>
</div>
Hide it after a second(giving some time for image to load)
$(".gallery img").each(function () {
$(this).attr("src",$(this).attr("src").replace("200/200", "400/400"));
setTimeout(function(){
$(".overlaydiv").hide();
},1000);
});
Check out this fiddle

JavaScript How to make an image to change color onmouseover?

I have a button and an image and want them to change color onmouseover.
The button changes color fine:
<script>
function secondColor(x) {
x.style.color="#000000";
}
function firstColor(x) {
x.style.color="#ffaacc";
}
</script>
<input onmouseover="secondColor(this)" onmouseout="firstColor(this)" type="submit"><br>
How can I do the same thing with the image? Is there any way:
<img src="..." ......
Or do I have to have a second image to replace the first one onmouseover and this is the only way?
If you don't care that much about supporting older browsers, you could use the new CSS3 filter brightness. In chrome, you could write something like this:
var image = document.getElementById('img');
image.addEventListener('mouseover', function() {
image.setAttribute('style','-webkit-filter: brightness(1.5)');
}, false);
image.addEventListener('mouseout', function() {
image.setAttribute('style','-webkit-filter: brightness(1.0)');
}, false);
I don't recommend this approach, though. Using another picture while hovering would be a better solution.
I know that this is old, but you don't need two images. Checkout my example using one image.
You can simply change the position of the background image.
<div class="changeColor"> </div>
JavaScript
var dvChange = document.getElementsByClassName('changeColor');
dvChange[0].onmouseover = function(){
this.style.backgroundPosition = '-400px 0px';
}
dvChange[0].onmouseout = function(){
this.style.backgroundPosition = '0px 0px';
}
CSS
.changeColor{
background-image:url('http://www.upsequence.com/images/multibg.png');
width:400px;
height:400px;
background-position: 0px 0px;
}
.changeColor:hover{
background-image:url('http://www.upsequence.com/images/multibg.png');
width:400px;
height:400px;
background-position: -400px 0px;
}
You can also try changing the opacity of the images onmouseover and onmouseout.
I don't have an example for that, but its super easy to find and I am sure it has be answered already on stack exchange somewhere.
In the JSFiddle below there is Javascript and non-Javascript examples.
http://jsfiddle.net/hallmanbilly/gtf2s8ts/
Enjoy!!
I think you have to use a second image. I recently cam across the following article describing how to do image crossfading on hover using css. Crossfading Image Hover Effect
You can change image SRC on mouse over, you can load two images and use fade effects to "change" them. But better, you can use image as DIV background, make sprite and just move BG on mouse over.
Loading of two different images bring you to disappearing when hover and second image loading. Better do not use JS at all. Make sprite from two images, put it as BG of DIV and write two CSS for DIV, normal and when hover.
If you have access to JQuery use hover function. If you want to change image
$('#imageid').hover(function(){
//change image or color or opacity
$(this).attr('src', newImageSrc);
});
add this function in document ready function.

Protecting an Image from downloading by Right-Click

EDIT: In response to many comments I do know that there is no sure fire way to fully protect an image from being downloaded. This method is to prevent the casual user from downloading by simple right click. The best way probably would be simply copyrighting your images and if you are very concerned would be using a service like Digimarc to digitally watermark your image. Now to the question:
I came across a site that is using a GIF overlay over their actual image so it protects the image from users right clicking and downloading the image (though you can still grab the actual image from within the code). The code they use to do this is:
<div><img src="-Transparent GIF File-" alt="" width="530" height="558"
border="0" original="-Actual Image Displayed-" /></div>
My question is the original tag is not a real tag and is used and translated by Javascript of some sort. I would like to replicate this on my site. Can someone help me find this script?
This is pointless. If a browser displays an image, it can be taken. Any attempt to prevent that is merely site overhead that can very easily be circumvented.
You're best protection is to put a copyright notice on the images themselves.
In any event, if you really want to swap the original attribute you can...
$(function() {
var o = $('img').attr('original');
$('img').attr('src', o);
});
Demo here
but... that doesn't do anything to prevent the user selecting and saving the image tied tot eh original attribute.
A simpler solution for what you're trying to accomplish is to add all of these attributes to the img tag:
ondrag="return false"
ondragstart="return false"
oncontextmenu="return false"
galleryimg="no"
onmousedown="return false"
Also, to optionally make the image print smaller, add this to the img tag:
class="imgPrint"
And include this related CSS:
#media print
{
.imgPrint
{
width: 40%;
}
}
You can do this without original tag also :
http://rainbow.arch.scriptmania.com/scripts/no_right_click.html
see this link.
I think this is what u want, this link may help you.
This is my implementation for a light protection of images.
It will create a transparent cover DOM element over the image (or text). If you disable javascript the image will be hidden and if you remove the cover the image will be hidden on mouse over. Also right click on images is disabled.
You can always printscreen, grab from the downloaded resources, etc, etc. This will only filter the most basic ways of download. But for a more convenient protection you have to hide the image path and render to a canvas object.
You can improve this, but there is always a method to get the image.
Tested on major browsers and working!
HTML
<div class="covered">
<img src="image.jpg" alt="" />
</div>
JAVASCRIPT + JQUERY
$('.covered').each( function () {
$(this).append('<cover></cover>');
$(this).mousedown(function(e){
if( e.button == 2 ) {
e.preventDefault();
return false;
}
return true;
});
$('img', this).css('display', 'block');
$(this).hover(function(){
var el = $('cover', this);
if (el.length <= 0) {
$(this).html('');
}
});
});
CSS
cover
{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.covered
{
position: relative;
}
.covered img
{
display: none;
}

image fade on hover + make image clickable

I'd like it so when I hover over the image, the entire image becomes a link rather than just the text inside. Can someone help me with this?
Javascript:
$('.thumbnail').hover(function() {
$('.thumbnail img').stop(true,true).fadeTo(400, 0.2);
$('.description').stop(true,true).fadeIn(400);
}, function() {
$('.thumbnail img').stop(true,true).fadeTo(400, 1);
$('.description').stop(true,true).fadeOut(400);
});
Here is the jsfiddle: http://jsfiddle.net/LDs6C/15/
Is there a reason why you aren't just surrounding the img tag with an a tag?
<img src="..." width="200"/>
Doing so will accomplish what you need without the extra markup.
Like this: http://jsfiddle.net/LDs6C/16/
I made the link a block element and set the dimensions to equal the size of the image.
I think you should be able to add an on click handler that takes you to the desired location, e.g.
$('.thumbnail img').click(function(){window.location='someurl';});

Categories