How to make an element appear then disappear on click - javascript

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();
});
});

Related

jQuery hover stuck

When I hover over an img which fades to another img and sroll off too fast, the fadeOut gets stuck and the fade stays. I've tried the .stop() as I've seen in other responses, but still won't work. Is there something else I can put instead of the .stop()?
<div class="grid big-square">
<a href="#"><img id="image2" src="img/fade/creo.png">
<img id="image1" src="img/creo.jpg"></a>
</div>
<script>
$("#image1").mouseenter(function () {
$(this).stop(true, true).fadeOut(1000);
});
$("#image2").mouseleave(function () {
$("#image1").stop(true, true).fadeIn(500);
});
</script>
I seem to remember having a similar problem when I was creating this website.
The solution is to use a combination of .hover() and .stop() to ensure that only one animation is running at a time, which I think you have. Also ensure that the mouseover image is on top of the other image, and just fade that one in and out. The image fading out gets 'stuck' because at some opacity the .mouseleave() stops firing and the .mouseenter() starts firing on the other image.
Something like:
$$ = $("#image1");
$$.hover(function () {
$$.stop().animate({
opacity: 0
}, 1000);
}, function () {
$$.stop().animate({
opacity: 1
}, 1000);
});
#image1 must be above #image2 for this to work, #image1 fades out to 'reveal' #image2 behind it. The code uses .animate() rather than .fadeIn() and .fadeOut() but the effect is the same.
Edit- to fade in another div after the end of the fadeoout animation use the complete call back of the animate function.
Something like:
$$ = $("#image1");
$$.hover(function () {
$$.stop().animate({
opacity: 0
}, 1000);
}, function () {
$$.stop().animate({
opacity: 1
}, 1000, function() {
$("#finalDiv").animate({ opacity: 1, 500 });
});
});
#finalDiv needs to be after the 2 <img />s in your html to appear above them.
I'm not sure how you're trying to accomplish this but I do know how it should be done.
Try this http://jsfiddle.net/xy5dj/
Make sure to listen for both events on the same element (preferably a wrapper element).
Take note that fadeOut actually removes the element from the rendered content (display: none) making sure that the mouse events won't fire on that element.
Side note:
A dirty trick that I used once (if you have to do this then you're doing something wrong) is to clear the style of the element after animation using the callback ability of the animate function i.e.
$('el').animate({opacity:0}, 500, function(){$(this).attr('style', '')});
fiddle
You should use the animation/transition in form:
.fadeTo( duration, opacity, complete )
where complete is callback function.

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.

how to remove hover on click

I'm working on a jQuery game. I have a 4 divs in a 2x2 design. The player needs to pick 1 option and verify with another button. The thing is, I have a hover effect adding a class which changes the background with a low opacity, and a click effect setting the background with a higher opacity. For divs 2, 3 and 4 it works fine - I hover and background changes color with opacity 0.3 and when I move the mouse out, it goes back to white. And when I click it, it changes the background to 0.4 and the hover doesn't affect them anymore. However, this is not working for the first div: the div changes background color on hover, but when I click it ,it keeps the hover color, and when I mouse out I see the click color, and every time I hover it changes the hover color again and so on.
Why is it happening only on div 1?
Code:
//hover effects
$(".respuesta1,.respuesta2,.respuesta3,.respuesta4").hover(
function () {
$(this).addClass("respuestahover");
},
function () {
$(this).removeClass("respuestahover");
});
//on click function for div1
$(".respuesta1").on("click", function () {
//if it hasnt been clicked, toogle class and change var to true
if (prendido1 == false) {
$(this).toggleClass("respuesta1b");
prendido1 = true;
//if any of the other divs are clicked by the time you are clicking unclicked 1, turn them off
if (prendido2 == true) {
$(".respuesta2").toggleClass("respuesta2b");
prendido2 = false;
}
if (prendido3 == true) {
$(".respuesta3").toggleClass("respuesta3b");
prendido3 = false;
}
if (prendido4 == true) {
$(".respuesta4").toggleClass("respuesta4b");
prendido4 = false;
}
//if is already clicked, turn off and change var to false
} else {
$(this).toggleClass("respuesta1b");
prendido1 = false;
}
});
The last part is repeated for every div "respuesta2", "respuesta3", etc..
Any idea?
EDIT
I was trying to clean up the code to make a jsFiddle and I think I got it to work:
http://jsfiddle.net/bqySN/2/
I'll just leave the code there if anyone is interested, be aware the code is unpolished and it need more generalisations.
EDIT 2
After some testing I actually found the problem:
if I alter the order of my css clases the app goes crazy:
This one is correct, with hover first
.respuestahover{
background-color:#f00;
opacity:0.2;
}
.respuestab{
background-color:#f00;
opacity:0.5;
}
This one is incorrect, hover second:
.respuestab{
background-color:#f00;
opacity:0.5;
}
.respuestahover{
background-color:#f00;
opacity:0.2;
}
I'm not really sure why it is behaving like that, but I'm glad I figure it out.
You are adding a class on hover... why would you do that via javascript if you can just use the :hover state from css? For example:
#foo .element p { color: red; }
#foo .element:hover p { color: blue; }
EDIT:
Sorry, I miss the original question.
If you want to remove the hover effect after clicking, you have lot of different ways to do this. You can remove the class defined with the hover via css, or if you want a jQuery solution you can use mouseenter/mouseleave with .on and then unbind with off.
See the following fiddle example.
You should simplify the bindings to just target them a little more generically, then remove the hover classes on all of them:
$(".respuesta").on("click", function (index) {
$(this).removeClass("hover");
// do other things
});
You can also use the index to find which number they are if they're in a list.
if you want the hover to not override the click, give the click an active class and tell the hovers to work on everything but them:
$('.respuesta:not(.active)').hover(function() {
// do something
}

Javascript move div onClick

I'm trying to get a div #sidebar that rests above my main #stream div to move from position left: 565px; to position left: 0px; onClick of one image in the #sidebar div (the red arrow in the images below), and do the reverse onClick of the same image. I know I have to use JavaScript, but I have no idea what the code would be. If possible, I would like to animate the div move too.
The pre-clicked state (the arrow will be my link):
The post-clicked state:
Thanks in advance!
If you want to animate it using animate have a look at this. It should get you pointed in the right direction:
http://jsfiddle.net/3DpfJ/5/embedded/result/ - Full screen result
http://jsfiddle.net/3DpfJ/5/ - source code
So what I simply did was this:
$(function()
{
var expanded = false;
$('#sidebar').click(function()
{
if (!expanded)
{
$(this).animate({'left' : '0px'}, {duration : 400});
expanded = true;
}
else
{
$(this).animate({'left' : '565px'}, {duration: 400});
expanded = false;
}
});
});
This is probably the simplest way of doing it via animation. Duration is set to 400 so it will take 0.4 seconds to animate. Adjust as you please.
This script should be executed as soon as you load the page to ensure that the expand works. You will want to create <script type="text/javascript"></script> tag in the header and put the code there.
Hope it works for you.
$('#sidebar').click(function(){
$(this).animate({"left": "0"});
});
jquery uses toggle to handle this. It works better than a regular "animate" because it combines the hide and show into one function (toggle).
You might need to do some tweaking to fit your needs but this should get you started:http://jqueryui.com/toggle/

Timed transition between image swaps with JQuery?

I have this code:
$('.pic_windows img').mouseenter(function () {
$(this).effect('shake', {
times : 4,
distance : 5
}, 15).attr('src', $(this).attr('src').replace(/.jpg/, '-1.jpg'))
});
$('.pic_windows img').mouseleave(function () {
$(this).attr('src', $(this).attr('src').replace(/-1.jpg/, '.jpg'))
});
where I'm using JQuery's .attr to swap the images, but I'd like the swapping to occur over the course of around 1 second. I've googled this and get all these complicated "CSS3 transitions with JQuery fallback" tutorials. Is there a way to 'animate' an .attr change?
I think I should do a fadeOut while the other fadeIn but I don't know how to write it, as I'm almost a complete JQuery newbie. I have a number of these transitions to do over the course of several pages. It'd be a cinch if I needed to write this for just one instance.
UPDATE On mouseenter, the image shakes and then should during this shake, fade from one picture to its swapped picture. On mouseleave, the image should just fade back to the original picture. Unfortunately I have also found that the shake effect is breaking on IE, all versions, as well as the image swap (it doesn't see image 2 at all)
No, you cannot animate an attribute change. What you can do is clone an element, change an attribute and transition between them.
var target = $(this).fadeOut();
var src = target.attr('src').replace(/-1.jpg/, '.jpg');
var copy = target.clone()
.attr('src', src)
.hide()
.insertAfter(target)
.fadeIn();
EDIT: Thank you for clarifying your intentions, I would advise not playing with the 'src', which will essentially require building a small stateful plugin. Instead, stick with the desired effect here, reveal an image on hover. jsFiddle
HTML
<div class="shaker">
<img src="http://lorempixel.com/output/nature-q-c-360-240-3.jpg" />
<img class="hover" src="http://lorempixel.com/output/technics-q-c-360-240-9.jpg" />
</div>​
CSS
.shaker {
position: relative;
}
.shaker img {
position: absolute;
}
.hover {
display: none;
}
JS
$('.shaker').hover(function () {
$(this).effect('shake', {
times: 4,
distance: 5
}, 15);
$(this).find('.hover').fadeIn();
}, function () {
$(this).find('.hover').stop().fadeOut();
});​
http://jsfiddle.net/eHQ3t/13/

Categories