I have this on HTML:
<script type="text/javascript" src="./scripts/changeImage.js"></script>
<img id="myimage" onclick="changeImage()" src="./images/avatars/1.png"/>
This is the function
var cc=0;
function changeImage(){
if(cc==-1){
cc=0;
document.getElementById('myimage').src="./images/avatars/1.png";
} else if (cc==0){
cc=1;
document.getElementById('myimage').src="./images/avatars/2.png";
} else if (cc==1){
cc=2;
document.getElementById('myimage').src="./images/avatars/3.png";
} else if (cc==2){
cc=0;
document.getElementById('myimage').src="./images/avatars/4.png";
}
}
I must click 2 times to change the image. I tried some tricks but nothing.
i must click 2 times to change the image ...
At a guess, I'd say that cc starts out being -1, and so you follow this branch through your code:
cc=0;
document.getElementById('myimage').src="./images/avatars/1.png";
Since that's setting the same path that's already on the image, nothing changes. But then cc is 0, so the second click follows the next branch.
BTW, this is what switch statements are for:
function changeImage() {
switch (cc) {
case -1:
document.getElementById('myimage').src = "./images/avatars/1.png";
break;
case 0:
document.getElementById('myimage').src = "./images/avatars/2.png";
break;
case 1:
document.getElementById('myimage').src = "./images/avatars/3.png";
break;
case 2:
document.getElementById('myimage').src = "./images/avatars/4.png";
break;
}
cc = cc == 2 ? 0 : cc + 1;
}
Or a map:
var imageMap = {
-1: "./images/avatars/1.png",
0: "./images/avatars/2.png",
1: "./images/avatars/3.png",
2: "./images/avatars/4.png"
};
function changeImage() {
document.getElementById('myimage').src = imageMap[cc];
cc = cc == 2 ? 0 : cc + 1;
}
In both of the above, I've replicated the logic of your if/else series, but note that the logic of your if/else series never lets you get back to 1.png.
Also note that I'm assuming the real image paths are more complex, because otherwise you'd just want to key off the fact that you have 1.png, 2.png, etc.
Related
I'm currently working on my html works, where I try to change the video source using Javascript.
Here is my video element.
<div>
<video id="songVid" onmouseover="controlsVid()">
<source src="../front-end/assets/media/video/vidio.mp4.mp4" >
<track default src="../front-end/assets/media/subtitle/New folder/sub.vtt">
</video>
</div>
And here is the javascript code.
var x = 1;
var nextVid = document.getElementById("nextVid");
nextVid.onclick = function() {
if (x === 1) {
opVid.src = "../front-end/assets/media/video/Moon Halo Honkai Impact 3rd Valkyrie Theme_480p.mp4";
opVid.play();
var x = x + 1;
}
else if (x === 2) {
opVid.src = "../front-end/assets/media/video/Honkai Impact 3rd Valkyrie Theme Rubia Performed by Zhou Shen Honkai Impact 3rd_480p.mp4";
opVid.play();
}
else {
alert("Something went wrong");
}
}
var backVid = document.getElementById("backVid");
backVid.onclick = function() {
if (x === 0) {
alert("End of the playlist");
}
else if (x === 2) {
opVid.src = "../front-end/assets/media/video/Moon Halo Honkai Impact 3rd Valkyrie Theme_480p.mp4";
opVid.play();
x = x - 1;
}
else if (x === 1) {
opVid.src = "../front-end/assets/media/video/COVER Tak Ingin Usai Mythia Batford _480p.mp4";
opVid.play();
x = x - 1;
}
}
So, the script will run when these button clicked.
<div class="css-button-center">
<button class="css-button" id="backVid"><i class="gg-play-slow-o flip"></i></button>
<!-- <button class="css-button" id="slowVid"><i class="gg-play-backwards"></i></button> -->
<button onclick="playVid()" class="css-button"><i class="gg-play-play-o"></i></button>
<button onclick="pauseVid()" class="css-button"><i class="gg-play-pause-o"></i></button>
<button onclick="stopVid()" class="css-button"><i class="gg-play-stop-o"></i></button>
<!-- <button class="css-button" id="fastVid"><i class="gg-play-forwards"></i></button> -->
<button class="css-button" id="nextVid"><i class="gg-play-fast-o"></i></button>
</div>
The script has a variable x where it's value will increase by 1 everytime the button with id next/back vid clicked. But, on these script, the value of x wont increase. Everytime the button clicked, it still uses the var x = 1; rather than the x value inside the if function. so it'll only change the source with the 2nd source and wont continue to the next src. Is there any solution for the javascript? because i think the problem is only on var x inside the Javascript.
In your next function you have declared a new variable which happens to be called 'x'. By using the var keyword you opened a new spot in memory and this variable is scoped to the function nextVid.onClick().
If you use VisualStudio code or webstorm to write your code you will probably get a little warning that it hides the global member.
Looking at your logic, is it correct that you want to show different videos when x == 2 based on clicking the next or previous button? If not and that is a mistake i would refactor the repeated structure to something like this
var x = 1;
var nextVid = document.getElementById("nextVid");
// better yet make this a named function
nextVid.onclick = function() {
videoToPlay();
x += 1;
}
var backVid = document.getElementById("backVid");
// better yet make this a named function
backVid.onclick = function() {
videoToPlay();
x -= 1;
}
function videoToPlay() {
// better yet pass in your video object instead of looking for it from a higher scope
// better yet you could have an array of your videos and then just look up the index based on the value of 'x'
switch (x) {
case x === 0:
alert("start of play list");
break;
case x === 1:
opVid.src = "../front-end/assets/media/video/Moon Halo Honkai Impact 3rd Valkyrie Theme_480p.mp4";
break;
case x === 2:
opVid.src = "../front-end/assets/media/video/Honkai Impact 3rd Valkyrie Theme Rubia Performed by Zhou Shen Honkai Impact 3rd_480p.mp4";
break;
case x === 3:
opVid.src = "../front-end/assets/media/video/COVER Tak Ingin Usai Mythia Batford _480p.mp4";
break;
default:
alert("something went wrong");
}
opVid.play();
}
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">
I'm trying to load gif images into a jssor slider via code, but didn't work with my code and i don't know why.
The purpose is that each image refreshes when shown, cause the gif animation is not a loop, i have to do it this way.
Thanks in advance, here i put the code that is changing the images:
The variables wich will contain the images...
var imagen1 = new Image();
var imagen2 = new Image();
var imagen3 = new Image();
imagen1.src = "./1.gif";
imagen2.src = "./2.gif";
imagen3.src = "./3.gif";
And the code to change them...
function OnSlidePark(slideIndex, fromIndex) {
switch (slideIndex) {
case 0:
$('#i1').attr('src', imagen1.src);
break;
case 1:
$('#i2').attr('src', imagen2.src);
break;
case 2:
$('#i3').attr('src', imagen3.src);
break;
}
}
By the way, the sources and the Id's are working correctly
Will the following codes work?
function OnSlidePark(slideIndex, fromIndex) {
switch (slideIndex) {
case 0:
$('#i1').attr('src', '');
$('#i1').attr('src', imagen1.src);
break;
case 1:
$('#i2').attr('src', '');
$('#i2').attr('src', imagen2.src);
break;
case 2:
$('#i3').attr('src', '');
$('#i3').attr('src', imagen3.src);
break;
}
}
I'm building a "game" where a user clicks on an image and a number is randomly generated. With this number an image is assigned and displayed. Essentially a Rock, Paper, Scissors game. I'm just trying to get the random image to display. However I'm confused as how to go about setting the variable and then displaying it.
Originally I tried creating a variable that inside the switch would be something as follows
case 1:
cpuChoice = <img id="rock" src="rock.jpg" name="rock" width="265" height="250" />
break;
And then do a $("#result").html(cpuChoice); (result being a div id) However I had no luck with that. Further research seemed to suggest I have to store images in a cache, which is what my code currently is set up for. Though I don't believe I'm understanding how to utilize it properly.
The images I'm using are stored in a file with the pages.
Below is an example of my current javascript page.
$(document).ready(function(){
var cpuImage = new Image();
rock.src = 'rock.jpg';
paper.src = 'paper.jpg';
scissors.src = 'scissors.jpg';
lizard.src = 'lizard.jpg';
spock.src = 'spock.jpg';
$("#paper").click(function(){
var ranNumberOne = 1 + Math.floor(Math.random() * 5);
// the switch is for assigning the image based on what number is generated
switch(ranNumberOne){
case 1:
document['rock'].src = rock.jpg;
break;
case 2:
document['paper'].src = paper.jpg;
break;
case 3:
document['scissors'].src = scissors.jpg;
break;
case 4:
document['spock'].src = spock.jpg;
break;
case 5:
document['rock'].src rock.jpg;
break;
}
document.['blank'].src =cpuImage.src;
});
blank is just the id of a temporary image I have. the code for it is as follows
<img id="blank" src="blank.jpg" name="blank" width="265" height="250" />
I've done alert's to make sure my onclicks and the random number generator are both working, which they are. It appears that my problem is just getting the image that "the computer picks" to show.
Ok. A few issues are happening here, all of which are solvable. So...
$(document).ready(function(){
// You don't need an image object, since you're only
// determining a string for `src` and applying it to an existing
// image object
var cpuImage = "";
/* Below you're assigning `src` properties to objects that don't exist. */
rock.src = 'rock.jpg';
paper.src = 'paper.jpg';
scissors.src = 'scissors.jpg';
lizard.src = 'lizard.jpg';
spock.src = 'spock.jpg';
/* I see what you're trying to do,
but try going about it a bit differently, example: */
var imageBank = {
'rock' : 'rock.jpg',
'paper' : 'paper.jpg',
'scissors' : 'scissors.jpg',
'lizard' : 'lizard.jpg',
'spock' : 'spock.jpg'
};
$("#paper").click(function(){
var ranNumberOne = 1 + Math.floor(Math.random() * 5);
// the switch is for assigning the image based on what number is generated
switch(ranNumberOne){
// Assign your 'cpuImage' variable to the associated imageBank key
case 1:
cpuImage = imageBank['rock'];
break;
case 2:
cpuImage = imageBank['paper'];
break;
case 3:
cpuImage = imageBank['scissors'];
break;
case 4:
cpuImage = imageBank['lizard'];
break;
case 5:
cpuImage = imageBank['spock'];
break;
}
// Old:
document.['blank'].src =cpuImage.src;
// JQuery syntax (assuming you have an image with id `blank`)
// New:
$("#blank").attr('src',cpuImage);
});
Keep in mind, using things like a dictionary AKA an object as an associative array (which the imageBank variable is) helps to include a bunch more information pertaining to rock, scissors, etc. in one easy-to-maintain place. You can add additional info as well, which will save you time and code in the future.
Hope this helps and best of luck!
In honor of Sheldon Cooper, this FIDDLE might help.
JS
$('.clickme').on('click', function(){
var randimage = Math.floor(Math.random() * 5) + 1;
$('.putmehere').html('');
$('.random1').html(randimage);
$('.holder img#i' + randimage).clone().appendTo('.putmehere');
});
html
<div id="container">
<img id="blank" src="blank.jpg" name="blank" width="265" height="250" />
</div>
js
$(function () {
$("#container")
.attr("data-name", $("img", this).attr("id"))
.on("click", function (e) {
var options = ["rock", "paper", "scissors", "lizard", "spock", "blank"];
var r = (function (n) {
return options[(n + Math.floor(Math.random() * options.length - n))]
})(1);
$("img", this).attr({
"id": r,
"name": r,
"src": r + ".jpg"
}).parent().attr("data-name", r);
});
});
jsfiddle http://jsfiddle.net/guest271314/e3EXs/
I am trying to code a menu bar for my site in JS - the problem I'm having is that I am using a variable as a 'which category is unfolded' switch, and it does not seem to register. Firebug seems to tell me it's not defined, and or stays zero.
var navOpen = 0;
$(function() {
///////////bunch of other functions here
//When designWork is clicked
$(".designwork").click(function(){
switch(navOpen)
{
case 0:
$(".navsub:hidden",this).slideDown("slow");
navOpen = 1; break;
case 1:
break;
case 2:
$("div.artProjects .navsub").slideUp("fast");
$(".navsub:hidden",this).slideDown("slow");
navOpen = 1; break;
default:
break;
}
});
//When artProjects is clicked
$(".artprojects").click(function(){
switch(navOpen)
{
case 0:
$(".navsub:hidden",this).slideDown("slow");
navOpen = 2; break;
case 1:
$("div.designWork .navsub").slideUp("fast");
$(".navsub:hidden",this).slideDown("slow");
navOpen = 2; break;
case 2:
break;
default:
break;
}
});
});
For a reason that is probably obvious, but I'm not seeing it, both menus open when clicked in the manner they should, but they do not close the other menu... help me out here, what am I missing?
$("div.designWork .navsub") should be $("div.designwork .navsub")
and
$("div.artProjects .navsub") should be $("div.artProjects .navsub")
capitals ...
Well, I think it has to do with the fact that in both cases you refer to ".navsub:hidden" without specifying precisely which navsub you really mean. You probably want to add either div.designWork or div.artProjects in front of it to specify which menu should slidedown.