Nested function and else condition not working - javascript

I am practicing JS doing a project and have run into issues (again).
Just upfront, to explain what i want.
I have the top level buttons with nation names, on click a pic will fade into a container just for that. It gets the pic from the first array on line 1.This all works very well. However...
When that container is visible, I want a click handler on the "next" button to the right. This handler is one function (line 29-42) which animates the second div(.containsNext) by changing opacity and rotate values.
This function also calls another function (next, this should change the target div background with pics from the new Array) and has an if else statement.
The if condition works as it is supposed to.
The else condition does not run, even if i take out the nested next() function.
I think the error (console doesn't return one) on the next function is the lines 15 and 16, I know those lines look "funny":-)
And the if statement in the wrapper function does not work either.
How to fix this? Please make sure to select France, Italy or Croatia buttons, or the next button will not respond at all (do not know why either).
One more question on the side, what would be an economical way to store the pics for all the nations arrays selected/triggered by the next button?
Also how to do implement the proper nations array to be selected based on the top button nation selection?
Thank you guys
function
var imgLenght = 3;
var currentImg = 1;
function next() {
var imgContainer = document.querySelector(".containsNext");
if(currentImg > 0)
{
imgContainer.style.background = "url(" + "im[currentImg-1]" + ")";
currentImg = currentImg - 1;
}
}
Link to the pen:
http://codepen.io/damianocel/pen/gPggLB

use correctly nested quotes:
imgContainer.style.background = 'url("' + im[currentImg-1] + '")';

Related

How to switch between different HTML elements with the same onclick function?

Right now i have four images which are being dynamically presented on html. This is done via an onload function. Basically when i click on of those wheels I would like the image to change for around one second then go back. But right now only one wheel changes colour which is quite annoying.
function setWheels() {
document.querySelector(".blue-wheel").innerHTML = "<img src='blue-dark.svg.svg' onclick='buttonEvent()'>";
document.querySelector(".red-wheel").innerHTML = "<img src='red-dark.svg.svg' onclick='buttonEvent()'>";
document.querySelector(".green-wheel").innerHTML = "<img src='green-dark.svg.svg'>";
document.querySelector(".yellow-wheel").innerHTML = "<img src='yellow-dark.svg.svg'>";
}
function buttonEvent() {
if (document.querySelector(".blue-wheel")) {
document.querySelector(".blue-wheel").innerHTML = "<img src='blue-light.svg.svg'>";
setTimeout(setWheels, 800);
}
else if (document.querySelector(".red-wheel")) {
document.querySelector(".red-wheel").innerHTML =<img src='red-light.svg.svg'>";
setTimeout(setWheels, 800);
}
}
I havnt added the other coloured wheels as i do predict that they will have the same effect. I do believe that the setTimeout may be one of the problems as I'm calling the setWheels function but the first if statement seems to be the only one that changes colour even when i click the other div.
Your if statements aren't checking anything useful. if(document.querySelector(".blue-wheel")) is only checking if that element is there, not if the image inside was clicked.
If you want to know which image was clicked, pass it in as a parameter to the function.
<img src='blue-dark.svg.svg' onclick='buttonEvent(this)'>
and in your javascript, just change the src for the image that was clicked and then set a timeout to change it back.
function buttonEvent(e) {
e.src = e.src.replace('dark', 'light');
setTimeout(() => {e.src = e.src.replace('light', 'dark')}, 800);
}
if you want to protect against fast clicking while the image is already highlighted (improve performance) you can add a return:
function buttonEvent(e) {
if (!e.src.includes('dark')) return;
e.src = e.src.replace('dark', 'light');
setTimeout(() => {e.src = e.src.replace('light', 'dark')}, 800);
}
You are missing a "
.innerHTML =<img src='red-light.svg.svg'>";
should be
.innerHTML = "<img src='red-light.svg.svg'>";
you can use a variable (let x=0) to count on what image are you on. then make function that will see what x = 0 so it will show the first image then add one to the x (like "x++")but before you show the image you need to remove the last one, so then you need to loop through the images (you can give the same class to the images) like ".forEach()" and in that function you can see if that image is on the page or is shown to the user then just remove it, then x =1 in that case just show the second image and so on. you can add "if" statement that will check "if x>=(image count)" when that happens then just "x=0" and it will reset

Button stops working when elements are placed after it (javascript)

I'm trying to make a text based idle game where multiple buttons are involved, and text around those.
Whenever I try to put text after the "Work" button it stops working, stops calling the callback on click.
I tried putting the text in a separate div, which didn't work, I also tried putting the button in its own div, which made things worse. The last thing I tried was putting the text written by the write functions (which made the formatting terrible) in a paragraph tag which somehow also didn't work.
I don't know what else to try. The only thing that doesn't seem to break it so far is putting other buttons after it.
I'm using a function to create buttons called createButton(), it takes in 3 arguments, the button text, the button ID, and the button callback, and to draw text I'm using a "custom" write function (details at bottom).
For the work button I'm passing in the work() function as the callback.
createButton function:
function createButton(text, id, callback){
// console.log(text + " " + id + " " + callback)
var button = document.createElement("button");
button.innerHTML = text; //create a button element
//var body = document.getElementsByTagName("body")[0];
gameDiv.appendChild(button); //set its parent to the game div
button.addEventListener ("click", callback); //add the callback as a listener
}
work function:
function work(){
money++;
//TODO: find better way of updating money counter
draw(); //redraw to update money counter
if(stage == 1){ //increment the current stage if needed (for pacing)
stage = 2;
setTimeout(function(){
buttonStage = 1;
createButton("Buy Box", "buyBox", buyBox);
}, 1000);
}
}
draw function:
function draw(){
clear(); //clear the screen
for(var i=0;i<stage;i++){
switch(i){
case 0:
writeln("Do this");
writeln(" ​|");
writeln(" |");
writeln("▼");
createButton("Work", "work", work); //recreating a button every second might be a problem, but i dont know how to get it to position properly otherwise
break;
case 1:
write("<div id=\"stage2\">");
writelnDiv("<br><br>Money: " + Math.round((money*100)/100), "stage2");
writelnDiv("", "stage2");
writelnDiv("Now do this", "stage2");
writelnDiv(" ​|", "stage2");
writelnDiv(" |", "stage2");
writelnDiv("▼", "stage2");
write("</div>")
if(buttonStage > 0){
createButton("Buy Box", "buyBox", buyBox);
}
break;
}
}
}
The write, writeDiv, writeln, and writelnDiv functions both just add the text to the div's innerHTML.
All code is here: https://js.do/Grimtin10/637778
The solution is probably simple, but I don't exactly know what I'm doing with javascript.
If any more info is needed to solve this I can provide it.
Alright, I figured out a solution.
Instead of using document.createElement I just created the button using HTML tags directly appending it to the div.
It's kind of an awful way of doing it, but it works.

Issue with jQuery .one() method

I've got a container that includes several icons the user can hover over and be shown a block of text next to it. I'm grabbing the blocks of text from an array and have a randomize function so that they're always shown a different block of text when revisiting the page.
I ran into an issue where every time you hover over an icon, it keeps adding more array elements, because the function gets called each time you hover over the icon. So I decided to use the one() method so the function only runs once, however that's where my real issue is. Using the one() method doesn't show ANY text, and I'm pretty sure it's due to the nested function I have.
You can test this out here: http://www.evanvolmering.com/bootstrap/docs/examples/carousel/eyeswideshut.html
In the banner a video will play, and shortly into it a little icon will appear in the bottom of left of the banner. Hovering over it will show some text. When you hover over it again it adds another array item, and so on. It works, but I don't want it to keep adding array items.
10 seconds later another icon will appear to the top right, which currently has the one() method applied to it. As you can see nothing happens when you hover over it. Not sure where to go from here.
My randomize code (which I got from another StackOverflow answer):
var numRandoms = 14;
function makeUniqueRandom() {
if (!uniqueRandoms.length) {
for (var i = 0; i < numRandoms; i++) {
uniqueRandoms.push(i);
}
}
var index = Math.floor(Math.random() * uniqueRandoms.length);
var val = uniqueRandoms[index];
uniqueRandoms.splice(index, 1);
return val;
}
My code which currently 'works' but keeps adding more array items on hover:
$('img.button1').hover(function(){
$('p.trivia1').fadeIn("slow");
$( 'p.trivia1' ).append(makeUniqueRandom());
},
function(){
$("p.trivia1").stop().fadeOut("slow");
});
My code that uses one() but doesn't do anything on hover:
$('img.button2').one("hover",function(){
$('p.trivia2').fadeIn("slow");
$( 'p.trivia2' ).append(makeUniqueRandom());
},
function(){
$("p.trivia2").stop().fadeOut("slow");
});
Use mouseenter/mouseleave instead of hover
$('img.button1').on('mouseenter',function(){
$('p.trivia1').fadeIn("slow");
$( 'p.trivia1' ).append(makeUniqueRandom());
}).on('mouseleave',function(){
$("p.trivia1").stop().fadeOut("slow");
});

setTimeout not working with onmouseout

First, here are the problematic lines of code:
<a onmouseover="hoverDisplay(this)" onmouseout="setTimeout(unHoverDisplay(), 3000);" href="http://rabbit.jpg">
Rabbit
</a><br>
Basically, I want the image to load and appear when I hover over the link, and I want the it to disappear after some time when I hover out of the link. The methods:
hoverDisplay(this)
unHoverDisplay()
display and remove the image, respectively, but when I tried to delay unHoverDisplay(), it didn't work; the image disappeared the moment my mouse hovered off the link.
I've tried adding and removing the semicolon after the setTimeout (not sure if the semicolon is necessary or not), and I tried delaying the hoverDisplay function as well, which did not work. Aside from the delay problem, the two functions work as intended.
This seems like a simple issue, but I can't figure out what I'm doing wrong. Help is appreciated. Thanks.
Not sure if this is necessary, but here are the implementations of the two functions:
//Display image for link that you hover over
var address; //Address of image
var toBeDisplayed; //Declaring img object
var maxHeight=screen.height;
var maxWidth=screen.width;
var invisible=document.getElementById("invisible"); //the div in which the image is contained
function hoverDisplay(imageLink)
{
address=imageLink.getAttribute("href"); //get address
toBeDisplayed=document.createElement("img"); //create img
toBeDisplayed.setAttribute("src", address); //give img the address
//Resize img if it doesnt fit on the screen
if(toBeDisplayed.height > maxHeight)
{
toBeDisplayed.style.height="" + maxHeight + "px";
}
else if(toBeDisplayed.width > maxWidth)
{
toBeDisplayed.style.width="" + maxWidth + "px";
}
invisible.appendChild(toBeDisplayed); //display image by adding it as a child to a div
invisible.style.visibility="visible"; //make div visible
toBeDisplayed.style.border="solid yellow 5px";
}
//Remove image once you hover out of the link
function unHoverDisplay()
{
//Removes all children of the div
while(invisible.firstChild)
{
invisible.removeChild(invisible.firstChild); //remove img by removing it as a child
}
invisible.style.visibility="hidden";
}
The trouble is that the parentheses after unHoverDisplay in your first argument to setTimeout are causing unHoverDisplay to be executed immediately. You simply want to pass the function by its identifier without the parentheses:
onmouseout="setTimeout(unHoverDisplay, 3000);"
You are passing a function as a parameter to setTimeout, not invoking it. Hence, you don't need those parentheses along with the function name, all that is required is the function name itself.
onmouseout = "setTimeout(unHoverDisplay, 3000);"

loop through array of dom objects and find first that match

I have a navigation bar at the top of my eform that skips to the next and previous div (page/section) but only if that div is visible. The divs are hidden unless activated with a checkbox. so the next button on the nav bar needs to work by always taking you to the next available div.
The following code works for the first button but these nav bars display at the top of each section so the next section has a next button on it running the same function (which doesn't work) i'm struggling to exlpain myself here so please shout if i'm not making sense. Here's my code.
function showNext(){
var pages = [document.getElementById("page2"),document.getElementById("page3")];
var next = ["page2marker","page3marker"];
for (var i=0; i<pages.length; i++){
if(pages[i].style.display == "block"){
window.location.hash = next[i];
}
}
}
Can i amend this function so that it will work for all buttons. I.e by always navigating to the next available div that is visible? I think i've probably missed a trick and a whole load of info but see what you think, any ideas?
Many thanks
You can achieve this using jQuery with the jQuery.next function - http://api.jquery.com/next/.
For a set of html like this:
<nav><a class="showNext">Show Next</a></nav>
<div class="content" style="display:none">I'm hidden</div>
<div class="content">I'm Visible</div>
You could use something like:
$('.showNext').bind('click', function(e) {
e.stopPropagation();
e.preventDefault();
window.location.hash = $(this).next('.content:visible').attr('id') + 'marker';
});

Categories