how to change an image based on an if statements requirements - javascript

var mpegArray = ["1.m4a", "2.m4a", "3.m4a", "4.m4a", "5.m4a", "6.m4a", "7.m4a", "8.m4a", "9.m4a", "10.m4a"];
var choice = Math.floor(Math.random() * mpegArray.length);
function btnPlay_onClick() {
var player = document.getElementById('sound');
player.src = mpegArray[choice];
player.play();
player.addEventListener('ended', function () {
if (player.ended) {
mpeg();
}
}, true);
}
function btnN1_onClick() {
var Audio1 = document.getElementById("audio1");
Audio1.play();
if (choice == 0) {
document.getElementById("btnN1").src = "1GR.gif";
ans.innerText = CORRECT;
}
else
document.getElementById("btnN1").src = "1RD.gif";
ans.innerText = INCORRECT;
}
hiya the code here is meant to get number tiles to change colour based on if the requirements of the if statements are met. here the if statement is asking if button 1 is pressed after the audio file 1.m4a is played change the colour of he tile to green if not change it to red

You might be better served changing the css with a background colour/image instead of the src attribute.
document.getElementById("btnN1").style.backgroundColor = "green";
or
document.getElementById("btnN1").style.backgroundImage = "url('1GR.gif')";
EDIT: GiaFil7 is right. You're missing a closing } after the second if statement which might be causing your issue.

Related

Javascript/ I am stuck with changing back to the original background

I am learning JavaScript and am now doing a homework assignment.
I need to find how to remve a background image from an element after the mouse leaves the element.
I wrote the function code, Dogimgleave(), and it does not update the HTML.
Here is the code, please help me...
<img class=size src = "Images/Dog.jpg" alt="Dog!" onmouseover="Dogimgon()" onmouseleave="Dogimgleave()">
function Dogimgon(){
document.getElementById("centertext").style.backgroundImage="url('Images/Dog.jpg')";
}
function Dogimgleave() {
document.getElementById("centertext").style.backgroundColor="#65F0B6";
}
You're leaving the background image set as an image, so you won't see the background colour. You can clear the image like this...
function Dogimgleave() {
var ct = document.getElementById("centertext");
ct.style.backgroundImage = ""; // this removes the background image
ct.style.backgroundColor="#65F0B6";
}
If you set the backogrund-image and background-color simultaneously one will cover the other one. You should have only one of them set at any time:
var elem = document.getElementById("centertext");
function Dogimgon(){
elem.style.backgroundImage = "url('Images/Dog.jpg')";
elem.style.backgroundColor = "";
}
function Dogimgleave() {
elem.style.backgroundImage = "";
elem.style.backgroundColor = "#65F0B6";
}
This can be of course simplified to setting just the background property:
var elem = document.getElementById("centertext");
function Dogimgon(){
elem.style.background = "url('Images/Dog.jpg')";
}
function Dogimgleave() {
elem.style.background = "#65F0B6";
}
Or alternatively you may have color always set (it would be visible through transparent parts of the image however) and alter only the image:
var elem = document.getElementById("centertext");
elem.style.backgroundColor = "#65F0B6";
function Dogimgon(){
elem.style.backgroundImage = "url('Images/Dog.jpg')";
}
function Dogimgleave() {
elem.style.backgroundImage = "";
}
By the way, unless you task is to do that exactly in JavaScript, you may easily achieave the same result with pure CSS:
#centertext {
background: #65f0B6;
}
#centertext:hover {
background: url('/Images/Dog.jpg');
}

How do I hide a div or image after 20 seconds of flashing in Javascript?

I am busy making a memory game, where an image is to be displayed to the user, and after some 10 seconds of the image flashing, it should hide and four options are to be shown for the user to choose either the correct or incorrect answer.
So far, all I have accomplished is to load the images and cycle through all the puzzles that my code can find.
What I'm trying to do now is to make the image flash and hide after some time, while also just refreshing that section of the page, and not the entire page.
I am using C# and a user control on my page.
What I have tried so far is only
<script>
var x;
function BlinkImage() {
x = 1;
setInterval(change, 2000);
}
function change() {
if (x === 1) {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = false;
x = 2;
}
else {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = true;
x = 1;
}
}
</script>
And on loading my puzzle for that instance (in code behind)
Page.ClientScript.RegisterStartupScript(typeof(game), "Start", "<script language=javascript> BlinkImage(); </script>");
Which does fire, as I can step through the code in debugging on Firefox. But my image does not flash or blink. I understand I am just using visiblity as my "blinker". I don't know what else to use exactly.
What can I do to make the image flash or blink for, say 20 seconds, then hide the image after that time has passed? Then repeat the process once the user has made a choice.
You can try the following (comments in code):
var blinkInterval = setInterval(change, 2000), // set the interval into a variable
image = document.getElementById('test'), // replace test with your client id: <%=imgMain.ClientID %>
x = 1;
function change() {
if (x % 2 === 1) { // see if it is odd or even by modding by 2 and getting remainder
image.style.display = 'none';
} else {
image.style.display = 'block';
}
x++; // increment x
if (x === 10) { // should have happened 10 times (which is 20 seconds with your intervals being at 2 seconds)
clearInterval(blinkInterval); // clear the interval (should end hidden as odd is display none and we clear beforethe 20th is run)
}
}
<div id="test">test</div>
After the code has finished, wherever the user is making their selection, you just need to reset the blinkInterval variable:
blinkInterval = setInterval(change, 2000); // notice no need for the var declaration when you reset this
Use style attribute and change if visible/hidden
function change() {
var image = document.getElementById('<%=imgMain.ClientID %>');
//check if visible
if (image.style.visibility=="visible") {
image.style.visibility="hidden";
}
else {
image.style.visibility="visible";
}
}
;
Try this:
function flashAndHide(img_id){
var img = $("#"+img_id);
var x = 0;
var inter = setInterval(function(){
if(x % 2 == 0){
img.hide();
}else{
img.show();
}
x += 1;
}
},1000);
if(x === 20){
img.hide();
clearInterval(inter);
}
}
Haven't tested this, but it should work,

I'm having a bit of trouble with the Javascript Onclick event when trying to toggle between images

So for one of my labs, I'm trying to get a blurred image with one src to appear as a clear image from a different source. So far I've only managed to change the blurred image to the clear image, but not the other way around.
So far, I have the if statement and a string indexOf as a part of my lab requirements. Now bear in mind that by my instructions, I'm not allowed to edit any HTML for this project.
function toggleImages(){
//(document.getElementById("clickimage").src = 'images/lab9_blurred');
//console.log(str.indexOf("clickimage"));
//var images = 'images/lab9_blurred.jpg';
var str = "images/lab9_blurred.jpg";
console.log(str.indexOf("blurred"));
var str = "images/lab9_clear.jpg";
console.log(str.indexOf("clear"))
//click it once, it's true, click it again, it's false. That's what should happen. But how do we do that?
//If image = "images/lab9_blurred.jpg" then for variable image we get clickimage, set variable name to lab 9 clear, and set image source to name.
//if (fake == true){
if (str.indexOf("blurred") == 12){
var image = document.getElementById("clickimage");
var name = "images/lab9_blurred.jpg";
image.src = name;
console.log(str.indexOf("blurred"));
}
else if (str.indexOf("clear") == 12)
{
var image = document.getElementById("clickimage");
var name = "images/lab9_clear.jpg";
image.src = name;
console.log(str.indexOf("clear"));
}
};
window.onload = init;
Hi try following code...
function toggleImages(){
var image = document.getElementById("clickimage");
if (image.src.indexOf("blurred") == 12)
{
var str = "images/lab9_clear.jpg";
console.log(str.indexOf("clear"))
}
else
{
var str = "images/lab9_blurred.jpg";
console.log(str.indexOf("blurred"));
}
image.src = str;
};
window.onload = init;

How can I change an image with onclick() & if statement repeatedly?

I am new to javascript and need some help with an issue.
I have 3 traffic light images that I want to change with each click. Go from green to amber with one click, then amber to red with another click, then from red to green, etc.
I have some code below, but it seems to go from green to red with the first click.
Any help is appreciated.
Thanks.
<!DOCTYPE html>
<html>
<body>
<button onclick="nextLight()">Click here</button>
<img id="demo" src="green.png">
<script>
function nextLight() {
var lights = ["blank.png", "green.png", "amber.png", "red.png"]
if (document.getElementById("demo").src == lights[1]) {
document.getElementById("demo").src = lights[2];
} else if (document.getElementById("demo").src == lights[2]) {
document.getElementById("demo").src = lights[3];
}
}
</script>
</body>
</html>
You have the lights array as the possible states. All you need is to iterate between them.
There is a problem with the time it takes to load the amber and red images for the 1st time, as they are loaded only when the state changes. I've added a little preloader to solve that problem.
fiddle demo - note that I use other images in the demo
var demo = document.getElementById("demo"); // get the demo element and cache it
var lights = ["green.png", "amber.png", "red.png"]; // array of lights srcs
var currentLight = 0; // current light index holder
lights.forEach(function(src) { // image preloader
new Image().src = src;
});
function nextLight() {
currentLight++; // add one to currentLight index
currentLight > 2 && (currentLight = 0); // if it's above 2 change it back to 0
demo.src = lights[currentLight]; // assign the url to the src
}
To do this, i think this way is much easier :
var lights = ['', '', '', ''];
var currentLight = 0;
// This version will loop (Go from red to blank at the end)
function nextLight() {
currentLight = (currentLight + 1) % lights.length;
document.getElementById("demo").src = lights[currentLight];
}
// This version do what you want (no loop, just display each image and then do nothing)
function nextLight() {
// Test if the next is not out of range
if(currentLight + 1 < lights.length - 1) {
document.getElementById("demo").src = lights[++currentLight];
}
}
I would suggest using a switch statement:
function nextLight() {
var demo = document.getElementById("demo");
var lights = [
"", // blank
"http://i.imgur.com/oisXdU3.png", // green light
"http://i.imgur.com/qmwYgq7.png", // orange light
"http://i.imgur.com/fs6Rl1W.png" // red light
];
switch(demo.src){
case lights[1] : demo.src = lights[2]; break;
case lights[2] : demo.src = lights[3]; break;
case lights[3] : demo.src = lights[1]; break;
}
}
<button onclick="nextLight()">Click here</button>
<img id="demo" src="http://i.imgur.com/oisXdU3.png" height="100">

How can I stop or pause one of the scripts I use when someone clicks on a specific link?

http://www.ultralocal.fr/refonte/test.php
As you can see, I have a menu with a few links. All of them, except one, launch a small script that changes the background color according to the onclick thing. The "Talweg" link work another way, it launches a bigger script that actually makes the background color change from time to time, progressively.
What I would like to know is how I can make the other links stop the Talweg script and just change the bgcolor for once.
the menu:
× Désœuvrements<br />
× Recettes<br />
× Talweg<br />
the simple script:
function changeBGC(color){
document.bgColor = color;
}
the bigger script that can be launched when one clicks on Talweg but I want to stop when one clicks on the other links.
// Set 1 dark to medium
// Set 2 light to medium
// Set 3 very dark to very light light
// Set 4 light to very light
// Set 5 dark to very dark
var fade_effect=4
// What type of gradient should be applied Internet Explorer 5x or higher?
// Set "none" or "horizontal" or "vertical"
var gradient_effect="none"
var speed=800
var browserinfos=navigator.userAgent
var ie4=document.all&&!document.getElementById
var ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/)
var ns4=document.layers
var ns6=document.getElementById&&!document.all
var opera=browserinfos.match(/Opera/)
var browserok=ie4||ie5||ns4||ns6||opera
if (fade_effect==1) {
var darkmax=1
var lightmax=127
}
if (fade_effect==2) {
var darkmax=180
var lightmax=254
}
if (fade_effect==3) {
var darkmax=1
var lightmax=254
}
if (fade_effect==4) {
var darkmax=204
var lightmax=254
}
if (fade_effect==5) {
var darkmax=1
var lightmax=80
}
var hexc = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F')
var newred
var newgreen
var newblue
var oldred
var oldgreen
var oldblue
var redcol_1
var redcol_2
var greencol_1
var greencol_2
var bluecol_1
var bluecol_2
var oldcolor
var newcolor
var firsttime=true
var stepred=1
var stepgreen=1
var stepblue=1
function setrandomcolor() {
var range=(lightmax-darkmax)
if (firsttime) {
newred=Math.ceil(range*Math.random())+darkmax
newgreen=Math.ceil(range*Math.random())+darkmax
newblue=Math.ceil(range*Math.random())+darkmax
firsttime=false
}
oldred=Math.ceil(range*Math.random())+darkmax
oldgreen=Math.ceil(range*Math.random())+darkmax
oldblue=Math.ceil(range*Math.random())+darkmax
stepred=newred-oldred
if (oldred>newred) {stepred=1}
else if (oldred<newred) {stepred=-1}
else {stepred=0}
stepgreen=newgreen-oldgreen
if (oldgreen>newgreen) {stepgreen=1}
else if (oldgreen<newgreen) {stepgreen=-1}
else {stepgreen=0}
stepblue=newblue-oldblue
if (oldblue>newblue) {stepblue=1}
else if (oldblue<newblue) {stepblue=-1}
else {stepblue=0}
fadebg()
}
function fadebg() {
if (newred==oldred) {stepred=0}
if (newgreen==oldgreen) {stepgreen=0}
if (newblue==oldblue) {stepblue=0}
newred+=stepred
newgreen+=stepgreen
newblue+=stepblue
if (stepred!=0 || stepgreen!=0 || stepblue!=0) {
redcol_1 = hexc[Math.floor(newred/16)];
redcol_2 = hexc[newred%16];
greencol_1 = hexc[Math.floor(newgreen/16)];
greencol_2 = hexc[newgreen%16];
bluecol_1 = hexc[Math.floor(newblue/16)];
bluecol_2 = hexc[newblue%16];
newcolor="#"+redcol_1+redcol_2+greencol_1+greencol_2+bluecol_1+bluecol_2
if (ie5 && gradient_effect!="none") {
if (gradient_effect=="horizontal") {gradient_effect=1}
if (gradient_effect=="vertical") {gradient_effect=0}
greencol_1 = hexc[Math.floor(newred/16)];
greencol_2 = hexc[newred%16];
bluecol_1 = hexc[Math.floor(newgreen/16)];
bluecol_2 = hexc[newgreen%16];
redcol_1 = hexc[Math.floor(newblue/16)];
redcol_2 = hexc[newblue%16];
var newcolorCompl="#"+redcol_1+redcol_2+greencol_1+greencol_2+bluecol_1+bluecol_2
document.body.style.filter=
"progid:DXImageTransform.Microsoft.Gradient(startColorstr="+newcolorCompl+", endColorstr="+newcolor+" GradientType="+gradient_effect+")"
}
else {
document.bgColor=newcolor
}
var timer=setTimeout("fadebg()",speed);
}
else {
clearTimeout(timer)
newred=oldred
newgreen=oldgreen
newblue=oldblue
oldcolor=newcolor
setrandomcolor()
}
}
Thanks
The longer-running script keeps re-executing itself with selfTimeout. If you want to stop it, all you need to do is call clearTimeout on the returned variable:
clearTimeout(timer)
Of course, you may need to be a bit more careful, because the script may be in the middle of the execution when you clear the timeout. One way to deal with it would be to set a flag indicating that the script need not be re-executed again. You can pull variable declarations out of the functions to make the code easier to read. So your code can look like this:
//variable declaration for use in fadebg function
var timer;
//variable declaration for the flag
var contBg = true;
//stop your previous script
function stopRandomBg() {
clearTimeout(timer);
contBg = false;
}
//changes to fadebg function
function fadebg() {
...
//change this line
//var timer=setTimeout("fadebg()",speed);
//to
if(contBg) {
timer=setTimeout("fadebg()",speed);
}
...
}
These additional changes will take care of the case when the script is in the middle of execution when you try to stop it - it will complete the execution pass and then stop.
Now all you need to do is to add onClick event listener to your link to call stopRandomBg function.
You have to make the timer variable global instead of local.
var timer;
then clear the timer when ever you call other links.
function changeBGC(color){
clearTimeout(timer);
document.bgColor = color;
}

Categories