Javascript not calling second function - javascript

I'm trying to make a main menu for a game. The first frame contains buttons "Start game" and "Quit". The second frame contains buttons "Start", "Back" and a clickable icon for turning the in-game music on or off.
In my onload function I'm adding event listeners to both the "start game" button and the clickable icon. However, it seems, that it only registers the first event listener as when I changed the order the "start game" button stopped working too. What am I doing wrong and am I missing something about handling input with DOM?
window.onload = function (){
document.getElementById("button_play").addEventListener("click", showInstructionPage);
document.getElementById("Link_sound").addEventListener("click", setSound);
}
function setSound(){
if(sound == 1){
document.getElementById("Icon_sound").setAttribute("src", "../media/vypnuty_zvuk.png");
sound = 0;
}
else{
document.getElementById("Icon_sound").setAttribute("src", "../media/zapnuty_zvuk.png");
sound = 1;
}
}
function showInstructionPage(){
//this part is long but works
document.getElementById("button_play").innerHTML = "Start";
document.getElementById("button_play").style.left = "350px";
var quit = document.getElementById("button_quit");
var back = document.createElement("a");
var id = document.createAttribute("id");
id.value = "button_back";
back.setAttributeNode(id);
var link = document.createAttribute("href");
link.value = "#";
back.setAttributeNode(link);
text = document.createTextNode("Back");
back.appendChild(text);
document.getElementById("menu").replaceChild(back, quit);
document.getElementById("button_back").style.left = "346px";
//add instructions and sound icon
var header = document.createElement("h1");
text = document.createTextNode("Instructions");
header.appendChild(text);
document.getElementById("menu").appendChild(header);
var id = document.createAttribute("id");
id.value = "Header_instructions";
header.setAttributeNode(id);
var goal = document.createElement("p");
text = document.createTextNode("Your goal is to get as many frogs to the other side of the river without losing all your lives. To do this, you need to avoid the traffic and alligators.");
goal.appendChild(text);
document.getElementById("menu").appendChild(goal);
var id = document.createAttribute("id");
id.value = "Paragraph_goal";
goal.setAttributeNode(id);
var instructions = document.createElement("p");
text = document.createTextNode("Move in any direction using the arrow keys");
instructions.appendChild(text);
document.getElementById("menu").appendChild(instructions);
var id = document.createAttribute("id");
id.value = "Paragraph_instructions";
instructions.setAttributeNode(id);
var soundLink = document.createElement("a");
var link = document.createAttribute("href");
link.value = "#";
soundLink.setAttributeNode(link)
var id = document.createAttribute("id");
id.value = "Link_sound";
soundLink.setAttributeNode(id);
var soundImage = document.createElement("img");
var id = document.createAttribute("id");
id.value = "Icon_sound";
soundImage.setAttributeNode(id);
var source = document.createAttribute("src");
source.value = "../media/zapnuty_zvuk.png";
soundImage.setAttributeNode(source);
soundLink.appendChild(soundImage);
document.getElementById("menu").appendChild(soundLink);
}
<html>
<head>
<meta charset="UTF-8">
<title>FROGGER</title>
<link rel="stylesheet" href="../css/styles.css" type="text/css">
<script type="text/javascript" src="../js/main.js"></script>
</head>
<body>
<div id="wrapper">
<div id="menu">
<img id="game_title" src="../media/title.png">
Start game
Quit
</div>
<canvas id="canvas" width="800" height="800"></canvas>
<img src="../media/menu_background.jpg" hidden="true" id="menuBackground">
</div>
</body>
</html>

The issue was, that when I called
document.getElementById("Link_sound").addEventListener("click", setSound);
inside the .onload function it couldn't assign the event listener because at the time of loading the page the clickable image doesn't exit yet, as it is only created using DOM after clicking a button. I solved it by moving the code snipped above to the bottom of the showInstructionPage() function after creating the image element.

Related

How to delay a submit event until another event is completed in JS?

I'm making a chrome extension that creates and pops up an overlay once a specific button is clicked. Clicking the button on the current page takes it to another one. I'd like to pop an overlay once the button is clicked, and only take it to the next page once the overlay is closed. This is my first project using JS so I'm a bit lost.
This is how I create the overlay
//injecting css
var link = document.createElement("link");
link.href = chrome.extension.getURL("css/overlay.css");
link.type = "text/css";
link.rel = "stylesheet";
document.head.appendChild(link);
//setting button's ID for easy referencing
var button = document.getElementsByName("proceedToCheckout")[0].setAttribute("id", "proceedToCheckout");
var overlay = document.createElement("DIV");
overlay.setAttribute("id", "overlay");
document.body.appendChild(overlay);
var url = chrome.extension.getURL("terry.jpg");
var img = document.createElement("IMG");
img.setAttribute("id", "terryImage");
img.setAttribute("src", url);
overlay.appendChild(img);
and this is how I go about the main click function
document.getElementById("proceedToCheckout").addEventListener("click", function()
{
alert("Do you really need that?");
document.getElementById("overlay").style.display = "block";
event.preventDefault();
//disable overlay once clicked
document.getElementById("overlay").addEventListener("click", function (){
document.getElementById("overlay").style.display = "none";
})
})
Since I'm using event.preventDefault(), it does not let me continue the event. Is there any other way I can go about this? Thanks.

Programmatically setting unique onclicks to imgs in a loop in Javascript

So I have this gallery page where I have multiple <img> tags with a unique picture. Clicking on the picture should take you to a another webpage with more info on that specific picture. Hence, all onclick()s are unique, depending on the src of the image.
Now, given the fact that all these <img> tags are virtually same save for picture, I decided to use JavaScript to make all of them in a loop, as seen below:
loadImageGalleryData
for (var i = 0; i < 21; i++) {
var imgSrc = "http://localhost:63342/Performance%20Task/Website/imgs/gallery/img/" + i + ".jpg";
console.log(imgSrc);
var imgDiv = document.createElement('div');
imgDiv.className = "img";
var descDiv = document.createElement('div');
descDiv.className = "desc";
var imgView = document.createElement('img');
imgView.src = imgSrc;
imgView.onclick = (function() {{openWebpage(imgSrc);}})();
console.log(imgSrc);
imgView.width = 300;
imgView.height = 200;
imgDiv.appendChild(imgView);
imgDiv.appendChild(descDiv);
document.getElementsByTagName('body')[0].appendChild(imgDiv);
}
The openWebpage() function in particular is this one:
openWebpage()
function openWebpage(src) {
var orig = window.document.title;
window.document.title = src;
open("imagePage.html");
}
The imagePage has a jscript which tells ITS OWN img and div tag to display the image, whose source is received from window.document.opener.title or somethign like that.
All the images get built, but the onclick() doesn't register. A peek in the developer mode in Chrome, and the images don't have an onlick() attribute.
Also, if I change this snippet of code:
imgView.onclick = (function() {{openWebpage(imgSrc);}})();
into this:
imgView.onclick = function() {openWebpage(imgSrc);};
The onlick() DOES register, but for every image simultaneously, with the src of the last image created. So when I click on Picture 1, it goes to the information of Picture 22. Same goes for every other picture. It's all the same info.
What am I doing wrong here?
EDIT: ADDITIONAL INFO
imagePage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/imagePage.css"/>
<script src="jscript/imageData.js"></script>
<script src="jscript/loadImageData.js"></script>
</head>
<ul>
<li>Home</li>
<li>Gallery</li>
<li>About</li>
<li>Contact</li>
</ul>
<body>
<div>
<h1 id="imageTitle">TESTTITLE</h1>
</div>
<div>
<img id="imageView">
</div>
<div class="boxed" id="imageDesc">
</div>
</body>
</html>
loadImageData
window.onload = function() {
var imageSrc = opener.document.title;
var imageDesc = map[imageSrc];
var imageView = document.getElementById("imageView");
var imageDescView = document.getElementById("imageDesc");
imageView.src = imageSrc;
imageDescView.innerHTML = imageDesc;
};
On the last iteration of your loop, you set imgSrc to the url of picture 22. So on the click event your function openWebPage fires with that url in the argument.
Try this.
imgView.addEventListener("click", function() {openWebpage(imgSrc);});

Javascript image upload, need description embed

the main thing that I am trying to do is get this simple image uploader to also allow the user to enter and store a description along with the image that is uploaded. Also some way to clear the images stored once they are in the preview.
What I currently have is
<html>
<body>
<script type='text/javascript'>
function main()
{
var inputFileToLoad = document.createElement("input");
inputFileToLoad.type = "file";
inputFileToLoad.id = "inputFileToLoad";
document.body.appendChild(inputFileToLoad);
var buttonLoadFile = document.createElement("button");
buttonLoadFile.onclick = loadImageFileAsURL;
buttonLoadFile.textContent = "Load Selected File";
document.body.appendChild(buttonLoadFile);
}
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
main();
</script>
</body>
</html>
Any help you can give would be greatly appreciated!
To get a description just create another input element within the form. Your code is not showing how you actually upload the image. So I guess it's a form with a POST action?
To clear the image, just add a button that removes the "img" element. For ease of use, just make the "imageLoaded" global and then remove that from the DOM when pressing that button.

Embedding should have been able to show the button

Please be advised that the following codes are generated by an engineer. (I don't have contact with the engineer right now)
Now here is the scenario. According to the engineer who had created this the whole collection of these scripts should be able to generate a button once edited properly and embedded to our website.
Before I implement this on our own website I want to test these codes to a simple page created through saving codes from our website. I ask the engineer if it is possible and he said yes.
Now here is the code that should be able to generate the button.
clickCall.js
(function () {
var createScriptElement = function (src, onload, onerror) {
var element = document.createElement("script");
element.type = "text\/javascript";
element.src = src;
element.onload = onload;
element.onerror = onerror;
return element;
};
var createLinkElement = function (src) {
var element = document.createElement('link');
element.href = src;
element.rel = 'Stylesheet';
element.media_type = 'text/css';
return element;
};
var createUI = function () {
var clickCallDiv = document.createElement('div');
clickCallDiv.style.cssText = 'width: 300px;height: 60px;position: fixed;z-index: 999;right: 20px;bottom: 320px;';
var call_btn = document.createElement("button");
call_btn.id = "dial_btn_call";
var session_div = document.createElement("div");
session_div.id = 'sessions';
var webcam_div = document.createElement("div");
webcam_div.style.cssText = 'height:0';
webcam_div.id = 'webcam';
var video_remote = document.createElement('video');
video_remote.id = 'remoteView';
video_remote.autoplay = 'autoplay';
video_remote.hidden = 'hidden';
var video_local = document.createElement('video');
video_local.autoplay = 'autoplay';
video_local.hidden = 'hidden';
video_local.muted = 'muted';
video_local.id = 'selfView';
webcam_div.appendChild(video_remote);
webcam_div.appendChild(video_local);
clickCallDiv.appendChild(call_btn); //add the text node to the newly created div.
var contain = document.createElement('div');
contain.appendChild(session_div);
contain.appendChild(webcam_div);
clickCallDiv.appendChild(contain);
return clickCallDiv;
};
var urls = {};
urls.rtcninja = 'rtcninja.js';
urls.jquery = 'jquery.js';
urls.i18n = "jquery.i18n.js";
urls.messagestore = "jquery.i18n.messagestore.js";
urls.jssip = 'jssip.js';
urls.init = 'init.js';
urls.gui = 'gui.js';
urls.css = 'style.css';
var rtcninja_script = createScriptElement(urls.rtcninja, function () {
// Must first init the library
rtcninja();
// Then check.
if (!rtcninja.hasWebRTC()) {
console.log('WebRTC is not supported in your browser :(');
} else {
document.body.appendChild(createUI());
}
});
var jquery_script = createScriptElement(urls.jquery, function(){
document.head.appendChild(i18_script);
document.head.appendChild(jssip_script);
document.head.appendChild(gui_script);
document.head.appendChild(init_script);
});
var i18_script = createScriptElement(urls.i18n, function(){
document.head.appendChild(messagestore_script);
});
var messagestore_script = createScriptElement(urls.messagestore);
var jssip_script = createScriptElement(urls.jssip);
var init_script = createScriptElement(urls.init);
var gui_script = createScriptElement(urls.gui);
var click_call_css = createLinkElement(urls.css);
document.head.appendChild(jquery_script);
document.head.appendChild(rtcninja_script);
document.head.appendChild(click_call_css);
})();
That script, when embedded, should be able to generate a button. The way he embedded the script on their website is through this
<script>
document.write('<script src="sourcefile/clickCall.js">/script>')
</script>
But this won't work on my side so I tried this
document.write('<sc' + 'ript src="clickCall.js">/sc' + 'ript>')
Now my first problem is that this script prevents all other scripts from loading, causing to have an empty output. another is that it won't display the expected button that it was suppose to show on the webpage. My solution to this problems was to implement DOM but I don't know how I'll implement it especially because I can't understand how it works and how to implement it. Could you kindly explain to me how DOM works and how am I going to implement it? Thanks
document.write when executed just writes the string and doesn't execute the inside script.
Hence, instead of this,
<script>
document.write('<script src="sourcefile/clickCall.js"></script>')
you can directly call your script.
<script src="sourcefile/clickCall.js"></script>

A few javascript issues: strange time dependence and images not loading 1st time

I'm trying to create a script for creating an overlay containing an image and some text, but i've run into some problems
1st: the image in the overlay doesn't appear when first clicked, but does on subsequent openings.
2nd: the scrollTo function only works if put in a timeout, otherwise it appears to do nothing.
If anyone could shed any light on this, or any other mistakes i've made, it would be much appreciated.
javascript:
var scrollY;
var i_w;
var i_h;
function showOverlay(filepath,num){
scrollY = document.body.scrollTop || document.documentElement.scrollTop;
hideOverlay();
document.getElementById("num").innerHTML ="image #: " + num + " click image to close";
var preload = new Image();
preload.src = filepath;
i_w = preload.width;
i_h = preload.height;
document.getElementById("blowup").width = i_w;
document.getElementById("blowup").height = i_h;
document.getElementById("blowup").src = filepath;
document.getElementById("overlay").style.display = "inline";
setTimeout("window.scrollTo(0,scrollY)",1);
setOverlayBounds(); //a function to orient the overlay div.
}
html:
<div id="overlay">
<center>
<img id="blowup" src="#" onClick="javascript:hideOverlay()">
<br>
<p id="num"></p>
<br>
</center>
</div>
css:
#overlay
{
display:none;
position:absolute;
background-color:#999;
border:medium;
border-color:#0F0
}
You should use the load event for the image to make sure, it finished loading before you execute your code. Also, you shouldn't use strings in connection with setTimeout. It's better to pass the function directly:
var preload = new Image();
preload.src = filepath;
preload.onload = function() {
i_w = preload.width;
i_h = preload.height;
document.getElementById("blowup").width = i_w;
document.getElementById("blowup").height = i_h;
document.getElementById("blowup").src = filepath;
document.getElementById("overlay").style.display = "inline";
setTimeout(function(){window.scrollTo(0,scrollY);},1);
setOverlayBounds(); //a function to orient the overlay div.
};
This should at least fix your first issue.

Categories