How to Hide an Image, if not clicked, in N seconds? - javascript

I have a button that when is clicked, an image is created using javascript and get prepended to a div (adds it inside a div).
var image = new Image();
var imageHtml = image.toHtml();
$('div.board').prepend(imageHtml);
function Image()
{
this.toHtml = function ()
{
return '<img src=\"myImage.png\" width=\"40px\" height=\"40px\" />';
}
}
This image can be clicked in 2 seconds then user will have 1 more score and if not clicked in that time, then the image should disappear.
How to do that in javascript?
Thanks,

function start_game(image){
var timeout = null;
image.onclick = function(){
clearTimeout(timeout);
//addScore();
};
timeout = setTimeout(function(){
image.onclick = null;
image.style.display = "none";
// remove the image from dom if needed;
}, 2000);
}
Demo: http://jsfiddle.net/UpNCb/

see this, just difference is you going to hide instead of link display
or
give id 'img_id' to your image
function hideimage() {
document.getElementById('img_id').style.display = 'none';
}
setTimeout(hideimage, 10000);

Use the function setTimeout() and the CSS property display or visibility.

Related

Pop up images on the page every few seconds

I have a page function that shows and hides images every 5 seconds.
Instead of these two images, I need to open random images from the list each time.
I added an array with images, tried to add the creation of an image in the popup() function, and the removal of the hidePopup() function, but nothing happened.
var images = new Array("http://dummyimage.com/100x100/100/fff",
"http://dummyimage.com/100x100/304/fff",
"http://dummyimage.com/100x100/508/fff",
"http://dummyimage.com/100x100/70B/fff",
"http://dummyimage.com/100x100/90F/fff",
"http://dummyimage.com/100x100/AA0/fff",
"http://dummyimage.com/100x100/CB0/fff",
"http://dummyimage.com/100x100/EC0/fff");
var randomImage = Math.floor(Math.random() * images.length);
popup();
function popup() {
document.getElementById("disclaimer").style.display = "block";
setTimeout(hidePopup, 5000);
}
function hidePopup() {
document.getElementById("disclaimer").style.display = "none";
setTimeout(popup, 5000);
}
<div id="disclaimer">
<div><img src="http://dummyimage.com/100x100/100/fff"></div>
<div><img src="http://dummyimage.com/100x100/304/fff"></div>
</div>
In the HTML file you should create a div with an id disclaimer
<div id="disclaimer"></div>
Then in the js file you should select the HTML element out of the popup function
const el = document.getElementById("disclaimer");
And create an enter code hereimage element out of the popup function
const img = document.createElement('img')
Then in the popup function you should create a random image every time the function get called with setTimeout to change the image src, set attribute src for image with random image number from images array, and append an image element to the div in HTML file
and call setTimeout with hidepop
function popup() {
randomImage = Math.floor(Math.random() * images.length)
img.setAttribute('src', images[randomImage])
img.setAttribute('alt', 'random')
el.appendChild(img);
setTimeout(hidePopup, 1000);
}
Then create a hidepop()
function hidePopup() {
setTimeout(popup, 1000);
}
And call popup function
popup()
Note :
In setTimeout function don't call the handler like that
setTimeout(hidePopup(), 1000);
that will cause Maximum call stack size exceeded error and you app will crashed
Set a promise then change the image randomly every N milliseconds.
const images = ["http://dummyimage.com/100x100/100/fff",
"http://dummyimage.com/100x100/304/fff",
"http://dummyimage.com/100x100/508/fff",
"http://dummyimage.com/100x100/70B/fff",
"http://dummyimage.com/100x100/90F/fff",
"http://dummyimage.com/100x100/AA0/fff",
"http://dummyimage.com/100x100/CB0/fff",
"http://dummyimage.com/100x100/EC0/fff"
];
const id = "disclaimer";
const imageElement = document.getElementById(id);
function wait(ms, value) {
return new Promise(resolve => setTimeout(resolve, ms, value));
}
function getRandomImageIndex() {
let randomImageIndex = Math.floor(Math.random() * images.length);
return randomImageIndex;
}
function setImage() {
let index = getRandomImageIndex();
var w = wait(5000, index);
w.then(function(index) {
console.log(index);
imageElement.setAttribute('src', images[index]);
}).then(function() {
imageElement.classList.toggle('hide-me');
return wait(5000, 1);
}).then(function() {
imageElement.classList.toggle('hide-me');
setImage();
});
}
// start it off
setImage();
.hide-me {
display: none;
}
<div id="disclaimer">
<div><img src="http://dummyimage.com/100x100/100/fff" alt="howdy"></div>
</div>
A better way to do this would be to change the source of the image.
var images = new Array("//dummyimage.com/100x100/100/fff",
"//dummyimage.com/100x100/304/fff",
"//dummyimage.com/100x100/508/fff",
"//dummyimage.com/100x100/70B/fff",
"//dummyimage.com/100x100/90F/fff",
"//dummyimage.com/100x100/AA0/fff",
"//dummyimage.com/100x100/CB0/fff",
"//dummyimage.com/100x100/EC0/fff");
popup();
function popup() {
randomImage = images[Math.floor(Math.random()*images.length)];
document.getElementById("changeThis").style.display = "block";
document.getElementById("changeThis").src = randomImage;
setTimeout(hidePopup, 5000);
}
function hidePopup() {
document.getElementById("changeThis").style.display = "none";
setTimeout(popup, 5000);
}
<img src="//dummyimage.com/100x100/100/fff" id="changeThis">
If you would prefer to not have the images disappear, you can remove style.display = "none";, and replace setTimeout(popup, 5000); with popup();
You should replace // with https:// or http:// if this is being accessed as a file.

How to override setTimeout?

This is part of a larger Three.js project but basically what I am trying to do is display a div for 5 seconds and then making it disappear based on user interaction. However, if the user triggers the interaction before the 5 seconds are up, the current div must disappear to be replaced by a new div and stay for 5 seconds. I am using jQuery for DOM interaction
Here is my code:
let lastdiv = 1;
function displayState(text){
if ($("#temp"+String(lastdiv))){
$("#temp"+String(lastdiv)).remove();
}
lastdiv += 1
body.append('<div id = "temp' + String(lastdiv) +'" class = "state">' + text + '</div>');
setTimeout(function(){
if($("#temp"+String(lastdiv))){
$("#temp"+String(lastdiv)).remove();
}
}, 5000);
}
Currently what happens is that the div shows up for 5 seconds. If there is no further interaction it disappears. However, if there is another interaction within that 5 seconds, the new div does show up but it disappears in 5 seconds since the previous div was displayed i.e. if I trigger the interaction 2 seconds after div1 is displayed, div2 will replace div1 but will disappear after 3 seconds.
If there is a better way of doing this please let me know. Thanks in advance.
Keep track of the timeout and cancel it.
const body = $("body");
let lastdiv = 1;
let timer = null;
function hideElement() {
if (timer) {
window.clearTimeout(timer);
$("#temp"+ lastdiv).remove();
timer = null;
}
}
function displayState(text){
hideElement();
lastdiv += 1
body.append('<div id = "temp' + lastdiv +'" class = "state">' + text + '</div>');
timer = setTimeout(hideElement, 5000);
}
displayState("aaa");
window.setTimeout(() => displayState("bbb"), 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Store the returned value of setTimeout in a variable and call clearTimeout to cancel it.
Demo:
var a = setTimeout(function() {
one.style.display = "none";
}, 5000);
one.addEventListener('click', function() {
clearTimeout(a);
this.style.display = "none";
two.style.display = "block";
setTimeout(function() {
two.style.display = "none";
}, 5000);
})
#two {
display: none;
}
<div id="one">This div will disappear in 5 seconds unless you click it</div>
<div id="two">This div will disappear in 5 seconds</div>

How to close a picture after displaying it?

I wrote JavaScript code that displays an image on click for my site. How do I add a way for it to close after users are done?
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display = 'block';
}
<img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" />
<button onclick="picture()">Apoyar</button>
https://jsfiddle.net/dmtakr3w/
To close that image after displaying it, you can remove the node by taking the parent element and invoking .removeChild(node); on the parent element.
function closePicture() {
var a = document.getElementById('QR');
var parent = a.parentNode;
console.log(parent);
parent.removeChild(a);
}
If you assign this function to a button you are able to close the image by clicking it:
<button onclick="closePicture()">Close</button>
You can also do a setTimeout() to automatically close the image after a certain amount of seconds or so:
// Removes the image after 5 seconds upon opening:
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display='block';
setTimeout(function() {
var a = document.getElementById('QR');
a.parentNode.removeChild(a);
}, 5000);
}
As Sag1v said in the comments, just add an on click event to the QR code tag and switch the display back to none.
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display = 'block';
}
function closePicture() {
var a = document.getElementById('QR');
a.style.display = 'none';
}
<img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" onclick="closePicture()" />
<button onclick="picture()">Apoyar</button>

Issues with resetting an interval

I have two elements. When I click the left element I want to change the right element into another element. If the left element is not clicked again the right element changes back to its original state. I've been able to make that happen, but I want to be able to click on that element again and have the interval I set restart. I feel like I'm close.
var changeImage = function(){
if(imageClicked == true){
var Img = document.getElementById('Img');
Img.setAttribute('src', "./images/img2.jpg");
imageTimeout = setTimeout(function(){
var Image = document.getElementById('Image');
Image.setAttribute('src', './images/image.jpg');
}, 3000)
imageClicked = false;
return imageTimeout;
} else {
imageClicked = true;
resetTimer();
}
}
var resetTimer = function(){
clearTimeout(imageTimeout);
window.setTimeout(imageTimeout, 3000);
}
random_image.addEventListener("click", changeImage, false);
The problem is that you are calling setTimeout(function ,delay) without a callback function.
The issue is in this line in the else block:
window.setTimeout(imageTimeout, 3000);
where imageTimeout is not a function, but the id of the timeout.
You need to create a separate function (let's call it timeoutFunction for example) with the timeout code and call it every time you invoke setTimeout.
After you create that function, and call it in the if block as well, change that line to:
imageTimeout = window.setTimeout(timeoutFunction, 3000);
from your code:
function timeoutFunction(){
var flowerImage = document.getElementById('flowerP');
flowerImage.setAttribute('src', './images/flowers.jpg');
}
by the way, you can define that flowerImage variable outside that function once instead of searching the DOM every time.
In order to clear a timeout, you need to call the clearTimeout function with the reference to the object that was returned by window.setTimeout. So you need to change your code to:
var resetTimer = function() {
clearTimeout(timeoutId);
createjs.Sound.stop(playSoundD);
timeoutId = window.setTimeout(imagetimeout, 3000);
console.log("I've been reset");
}

JavaScript changing image when hovering

I am trying to write a script, so that when someone hovers over an image, that same images changes to a different one, ie. I hover over up.png, and it changes to up_highlighted.png, when the mouse goes off the image it should change back.
However I can't seem to get it working despite all my attempts, here is the relevant code of what I have tried so far:
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up()\" onclick=\"increase_rating()\">";
function hover_up(){
$(document).ready(function() {
var oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').hover(function() {
//on hover of your element
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}, function() {
//when the cursor leaves your element
$('.thumbsbtn1').attr('src', oldSrc);
});
});
}
PS. I do not wish to use sprites.
Old School: http://jsfiddle.net/PAGUp/
var elem = document.getElementById('targetImg');
var oldSrc;
elem.onmouseover = function() {
oldSrc = elem.src;
elem.src = 'http://www.eclipse-developers.com/images/up_hover.png';
}
elem.onmouseout = function() {
if(typeof oldSrc !== 'undefined') {
elem.src = oldSrc;
}
}
I'm sure the jquery is more pithy. Essentially you need a variable to hold the 'old' src URL, and mouseover and mouseout handlers to set the new URL and back it out.
You don't have to wrap $(document).ready inside hover_up function. Note that I have removed onhover from HTML
Try
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onclick=\"increase_rating()\">";
$(document).ready(function() {
var oldSrc;
$(document).on('hover', '.thumbsbtn1', function () {
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}, function () {
$('.thumbsbtn1').attr('src', oldSrc);
});
});
try this
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up(this)\" onclick=\"increase_rating()\" onmouseout=\"hover_out(this)\">";
var oldSrc;
function hover_up(e){
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}
function hover_out(e){
$('.thumbsbtn1').attr('src',oldSrc);
}

Categories

Resources