Javascript Toggle not Working - javascript

I'm using Javascript to look for "#mode2" in the URL and if so, it will produce a different colored image with canvas. That part of the script is working fine. The issue is in the script that produces the toggle hyperlink. It will toggle the first time correctly (which makes sense as its a different part of the script) and then will toggle either once or twice depending on where it starts.
I.E. Blue is the default, so if the page loads on blue, it will toggle orange and then back to blue and then won't work, where as if its on orange it will just toggle to blue and then won't work.
I know its probably some stupid error in my code but I can't find it so if someone could help me out I would appreciate it a lot.
<script type="text/javascript">
function toggle(blue){
if (blue == 0) {
blue = 1;
}
else if (blue == 1) {
blue = 0;
}
if (blue == 0){
var container = document.getElementById("navi");
var content = 'back';
container.innerHTML= content;
}
else{
var container = document.getElementById("navi");
var content = 'back';
container.innerHTML= content;
}
}
var pathArray = document.URL;
if (pathArray.indexOf("mode2") != -1){
var blue = 0;
var container = document.getElementById("navi");
var content = 'back';
container.innerHTML= content;
}
else{
var blue = 1;
var container = document.getElementById("navi");
var content = 'toggle colors - back';
container.innerHTML= content;
}
</script>

Instead of this (for all occurrences):
onclick="toggle(blue);"
do this:
onclick="toggle('+blue+');"
Here is a fiddle: http://jsfiddle.net/YF4Nc/1/

Related

How can I put off everything in my code until a button is clicked?

Working on a JavaScript program, and the first thing that happens when run is asking the user whether they want to enter something using prompt()s, or using a textarea. The textarea option comes with a clickable button element to press once the user has entered everything they want into the textarea.
If this option is chosen, I want the rest of my program to not run until this button is clicked, and the user is confirming that they are finished with their input. Currently I have the button code within the selection part (where the user has chosen to use a textarea), as below:
if (trimmedResponse == 'manual') {
... (irrelevant code)
} else { //if paste is chosen
var createArray = function(howMany){
var pasteInput = document.createElement("TEXTAREA");
var makingArray = [];
document.body.appendChild(pasteInput);
pasteInput.rows = howMany;
let done = document.createElement("button");
done.innerHTML = 'Enter terms';
done.onclick = function(){
for (var j = 0; j < howMany; j++){
makingArray[j] = String((pasteInput.value).replace(/ /g,'').split('-')).split('\n');
}
pasteInput.style.display = 'none';
done.style.display = 'none';
}
document.body.appendChild(done);
return makingArray;
}
termArray = window.createArray(numOfTerms); //getting a variable holding the array from the prior function, to access later
}
The rest of the script.js file is made up of the regular subroutines - preload, setup, draw, and some initialisation and other small methods in the open scope before preload(), as below in a greatly reduced format:
let BG;
let translateEdit = document.createElement("button");
translateEdit.innerHTML = "Edit a translation";
translateEdit.style.position = 'absolute';
translateEdit.style.left = '50px';
translateEdit.style.top = '130px';
let list = "";
translateEdit.onclick = function () {
this.blur();
do {
replaceChoice = prompt("Which translation do you want to edit? (1-"+numOfTerms+") \n"+list+" \nOr enter any letter to leave this screen.");
} while (replaceChoice < 1 || replaceChoice > termArray.length)
termArray[replaceChoice-1][1] = prompt("What is the new translation for the term "+termArray[replaceChoice-1][0]+"?");
list = "";
for (let i = 0; i < numOfTerms ; i++){
list += ((i+1)+". ["+termArray[i][0] + "] - [" + termArray[i][1] + "]\n") //adds each term and translation in a user-friendly / clear display to the list variable for later display
}
alert("The term list currently looks as follows: \n"+list);
};
document.body.appendChild(translateEdit);
let temp1;
let temp2;
let temp3;
var performanceDisplay = "";
function preload() { //function loading image from file into variable
Helvetica = loadFont('Helvetica-Bold.ttf');
BG = loadImage('images/background.png');
}
function setup() { //function to create display/background using image file and dimensions and instantiate objects (character,terms,counters) as well as slider and icon to be displayed for it
alert("Below are the terms you have entered: \n" + list + "If any of the above are incorrect, use the edit buttons on the next screen to adjust terms or translations.");
speakericon = loadImage('images/speaker.png');
createCanvas(width, height);
... (further code in setup())
}
function draw() { //make background + objects visible on screen, allow them to act as they must, creating new terms when necessary, calling functions in class files such as player movement (calls all functions in classes throughout function) - all run every tick
image(BG, 0, 0, width, height); //set the display to the background image from BG variable in preload()
... (further code in draw())
}
In essence, I need to stop everything else from running until the button 'done' is clicked, and would appreciate any help with anything to achieve this.

Showing Hidden Image With Onclick Function

my objective is to have an image hidden until a button is pressed to then show the previously hidden image.
Right now I have an image in html with an Id of "yellowrose" that is hidden with this code:
<div id="yellowrose"><img src="https://i.imgur.com/ppfhZa6.jpg" style="visibility:hidden"></div>
In JS I have several things happening with the buttonx.onclick, but I can't seem to make the image visible. Here's my JS code:
var content = document.getElementById("content");
var buttonx = document.getElementById("show-more");
let yellowrose = document.getElementById("yellowrose");
window.onload = function(){
buttonx.onclick = function () {
document.getElementById("yellowrose").style.visibility="visible";
if(content.className == "open") {
//shrink the box
content.className = "";
buttonx.innerHTML = "Continue to the Sunlit Pavillion?";
} else{
//expand the box
content.className = "open";
buttonx.innerHTML = "As you wander through the garden grounds you notice a striking Yellow Rose";
}
}
}
Do you have any suggestions on how I can make the "yellowrose" image visible through the buttonx.onclick function? Thank you.
An id cannot contain a space.
As per MDN:
id's value must not contain whitespace (spaces, tabs etc.). Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID. In contrast to the class attribute, which allows space-separated values, elements can only have one single ID value.
Additionally, you are setting the visibility of #yellowrose, the container of the image, and not the image itself. To solve this, simply get the firstChild property:
var content = document.getElementById("content");
var buttonx = document.getElementById("showmore");
let yellowrose = document.getElementById("yellowrose");
window.onload = function() {
buttonx.onclick = function() {
document.getElementById("yellowrose").firstChild.style.visibility = "visible";
if (content.className == "open") {
//shrink the box
content.className = "";
buttonx.innerHTML = "Continue to the Sunlit Pavillion?";
} else {
//expand the box
content.className = "open";
buttonx.innerHTML = "As you wander through the garden grounds you notice a striking Yellow Rose";
}
}
}
.open{
visibility:visible !important;
}
<div id="yellowrose"><img src="https://i.imgur.com/ppfhZa6.jpg" style="visibility:hidden"></div>
<button id="showmore">Show More</button>
<div id="content">
content
</div>

Drag and drop event sometimes doesnt execute the DOM

I have a textarea that has the id = display
javascript:
<script>
function drag(event) {
event.dataTransfer.setData("text", this.event.target.src);
}
function drop(event) {
event.preventDefault();
let data = event.dataTransfer.files;
for (file of data) {
var l = document.getElementById('display').selectionStart;
var text = document.getElementById("display").value;
sub1 = text.substring(l,0);
var len = text.length;
var l2 = sub1.length;
sub2 = text.substring(len,l2);
var test = sub1 + file.name + sub2;
var end = document.getElementById("display").textContent = test;
alert(end);
}
}
function allow(event) {
event.preventDefault();
}
</script>
I type in some text and want to put the dragged file in between the text. When i run this code, the alert shows the correct content, but the DOM never updates.
This only occurs when i input text in the area myself. For example if text is already in the field and i drag and drop the DOM wont update even though the alert shows the correct content.
I have spent countless hours trying to debug this but cant seem to find a solution.
The demo below you will see if you type in the textarea it doesnt work with the drag and drop. But if you dont press any keys and just keep on dragging images it will work
Demo here
Thanks.
This line:
var end = document.getElementById("display").textContent = test;
Should be:
var end = document.getElementById("display").value = test;
.textContent is replaced with .value

use javascript onclick on a button to switch between two images based on the previous one

I have two images and I want a button which has an onclick event to switch the background image of a div I have, the problem is the first two clicks work but the third click still returns the second image instead of the first. I tried testing it with background color and it works fine, it switches between the two colors.
I would like a javscript only answer also.
Javascipt
(function() {
var clickMe = document.getElementById('ray');
var theBody = document.getElementById("container");
var image1 = "url(chidi.png)"
var image2 = "url(chidi2.jpg)"
var colorMe = function() {
if(theBody.style.backgroundImage == "" || theBody.style.backgroundImage == image2) {
theBody.style.backgroundImage = image1;
} else {
theBody.style.backgroundImage = image2;
}
console.log(theBody.style.backgroundImage);
}
ray.onclick = colorMe;
}());

How To Change Iframe source Based On Button State Using Javascript

I am trying to create a series of buttons for a web page that would function like toggle buttons (active/inactive) and would change the source of an iframe based on which combination of buttons are currently selected. So, for example, if I want someone to visualize a product that comes in:
three colors (Red, Green, Blue)
three material types (Metal, Plastic, Glass)
three sizes (Small, Medium, Large)
and I happened to have a separate webpage for each option that I want to show based on the current selections (27 possible combinations in this case), how would I go about doing that? Sorry, I am not very experienced with this, but I am trying to learn.
//Would I set the initial variables like this?
var Red = true;
var Blue = false;
var Green = false;
var Metal = true;
var Plastic = false;
var Glass = false;
var Small = true;
var Medium = false;
var Large = false;
...
//Then set the initial state of each button? (Sorry, not sure what this would look like.)
btnRed.active;
btnMetal.active;
btnSmall.active;
...
//Then make a conditional statement to make sure two variables and two button states cannot be true at the same time within each of the three categories? (Again, sorry not sure what some of this code would look like.)
if (btnRed.active){
Red = true;
Blue = false;
Green = false;
btnBlue.active = false;
btnGreen.active = false;
} else if (btnBlue.active){
Red = false;
Blue = true;
Green = false;
btnRed.active = false;
btnGreen.active = false;
} else if (btnGreen.active){
Red = false;
Blue = false;
Green = true;
btnBlue.active = false;
btnRed.active = false;
}
...
//Then set the iframe source based on the variable combination?
if (Red = true && Metal = true && Small = true){
document.getElementById('myIframe').src = "http://somesite.com";
}
...
Any help is appreciated. Thank you!
I am assuming you are using radio buttons.
$('input[type="radio"]').on("change", setIframe);
var setIframe = function() {
var url;
//computation of url
$('iframe').attr("src", url);
}
Here is the complete working code : Working Code

Categories