My onclick event is firing even without a click. I'm not sure why? Below is my code. The home panel should load first and when the user clicks the aboutButton they should be taken to the about panel.
JS Bin: http://jsbin.com/alebox/1/edit
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
function myOnloadFunc() {
var homePanel = document.getElementById("homePanel");
var aboutPanel = document.getElementById("aboutPanel");
var settingsPanel = document.getElementById("settingsPanel");
var gamePanel = document.getElementById("gamePanel");
var resultsPanel = document.getElementById("resultsPanel");
// All panels in app
var panels = [homePanel, aboutPanel, settingsPanel, gamePanel, resultsPanel];
// Show selected panel and hide all other panels
function showPanel(panel) {
for (var i = 0; i < panels.length; i++) {
if (panels[i] === panel) {
// Show panel
// this referred to global object, i.e. window
panels[i].style.display = "block";
} else {
// Hide
panels[i].style.display = "none";
}
}
}
showPanel(homePanel);
// CODE THAT IS GIVING ME A PROBLEM /////////////////////////
var aboutButton = document.getElementById("aboutButton");
aboutButton.onclick = showPanel(aboutPanel);
// CODE THAT IS GIVING ME A PROBLEM /////////////////////////
}
window.onload = myOnloadFunc;
</script>
</head>
<body>
<!-- homePanel -->
<div class="panel" id="homePanel">
<div align="center">
<p><strong>Web App</strong></p>
<p><a id="playButton">Play</a> <a id="aboutButton">About</a></p>
</div>
</div>
<!-- aboutPanel -->
<div class="panel" id="aboutPanel">
About panel
</div>
<!-- settingsPanel -->
<div class="panel" id="settingsPanel">
Settings panel
</div>
<!-- gamePanel -->
<div class="panel" id="gamePanel">
Game panel
</div>
<!-- resultsPanel -->
<div class="panel" id="resultsPanel">
Results panel
</div>
</body>
</html>
It's firing because you're calling it right away!
So you want:
aboutButton.onclick = function(){showPanel(aboutPanel);};
To attach a function to the event only the reference to the function should be given. You're actually calling the function when using ().
The code to bind the event should be:
aboutButton.onclick = showPanel;
Related
I'm totally lost as to where to begin here, how would I create a countdown button so that each time my button is clicked, it prints out the global variable and reduce it by 1 in the innerHTML and when it hits 0 it says BOOM?
I know I have to declare the variable outside but not sure what to do afterwards
JS:
var i = 20
function myFunction()
{
i = i--; // the value of i starting at 20
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script src="task6.js" type="text/javascript"></script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
</body>
</html>
I tryed this code and works fine
var i = 20;
function myFunction() {
myData = document.getElementById("mydata");
i = i - 1;
myData.textContent = i;
if(i <= 0) {//with <=0 the user if click again,after zero he sees only BOOM
myData.textContent = "BOOM!"
}
}
html code
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script src="task6.js" type="text/javascript"></script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 6 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript">
var i = 20;
function myFunction() {
var myData = document.getElementById("mydata");
i = i - 1;
myData.textContent = i;
if(i <= 0) {
myData.textContent = "BOOM!"
}
}
</script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Count Down </p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
</body>
</html>
It's good practice to not inline JS in the HTML so I'll provide an extra example to show how to separate it out using a couple of DOM selection methods:
let count = 20;
// grab the element with the mydata id
const mydata = document.getElementById('mydata');
// grab the button and attach an click event listener to it -
// when the button is clicked the `handleClick` function is called
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
if (count === 0) {
mydata.textContent = 'Boom';
} else {
mydata.textContent = count;
}
count--;
}
<body>
<p id="mydata">Countdown</p>
<button>Click</button>
<script src="task6.js" type="text/javascript"></script>
</body>
Reference
getElementById
querySelector
addEventListener
I'll assume you want to show the variable output and the BOOM at the <p id="mydata"> Count Down </p>, if I am mistaken correct me. So, something like this:
let i = 20;
const myData = document.querySelector("#mydata");
function myFunction() {
i = i - 1;
myData.textContent = i;
if(i === 0) {
myData.textContent = "BOOM!"
}
}
You almost got it whole,only missed the textContent and if part. If this is what you wanted to achieve. If this isn't what you were looking for, hit me up so I can correct it. Cheers :)
You need some way of displaying the number inside of your variable. One of the simplist ways to do this would be to set text to your paragraph tag using getElementById() and inner HTML. For example, after running your deincrement, on the next line you would do something like...
function myFunction()
{
i = i--; // the value of i starting at 20
document.getElementById("mydata").innerHTML = i;
}
This code simply grabs your "mydata" paragraph from the DOM and injects the number into the tag as html.
This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 6 years ago.
I'm having issues using Javascript to run a function. What I want to happen is I want the function to fire off when the user clicks a button. However, it fires off when the page loads.
Here is the entire code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<input type="submit" id="btn" value="Load">
<div id="description">
<div id="info">
<h1 id="title"></h1>
<p id="description"></p>
<ul id="list"></ul>
</div>
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
<script>
var btn = document.getElementById('btn');
var title = document.getElementById('title');
var description = document.getElementById('description');
var list = document.getElementById('list');
btn.onclick = load();
function load() {
alert("Working.");
}
</script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Right now, it obviously doesn't do much except fire off an alert box. But I'll by using it to load in a file via XMLHttpRequest object later. But right now, its not working the way it should.
I should also point out that the code works fine with an anonymous function, But the whole idea is to have a normal function. I'm just not sure why it would work with an anonymous function and not a normal one.
It should be
var btn = document.getElementById('btn');
var title = document.getElementById('title');
var description = document.getElementById('description');
var list = document.getElementById('list');
btn.onclick = load;
function load() {
alert("Working.");
}
DEMO
I am practicing Windows Phone development using WinJS and I have the following code which parses JSON received from a particular URL. And using the images to be bound to a list view in an HTML page,
JavaScript code:
WinJS.xhr({ url: urlToBeUsed }).then(
function (sportsResponse) {
var sportsJSON = JSON.parse(sportsResponse.responseText);
var listItems = sportsJSON.Videos.Data;
for (var i = 0; i < listItems.length; i++) {
var imageList = listItems[i].Items;
var count = imageList.length;
if (count > 0) {
listItems[i].Items[0].Images.forEach(imageIteration);
function imageIteration(value, index, array) {
var picture = value.Url;
var name = value.title;
sportsImageList.push({
title: name,
picture: picture
});
}
}
}
imageList.itemDataSource = sportsImageList.dataSource;
})
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- WinJS references -->
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<script src="/js/navigator.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<link href="/pages/home/home.css" rel="stylesheet" />
<script src="/pages/sports/sports.js"></script>
</head>
<body>
<!-- The content that will be loaded and displayed. -->
<div class="fragment homepage" style="width:100%;height:100%;padding:10px">
<div class="myTemplate" data-win-control="WinJS.Binding.Template">
<div class="myItem">
<img data-win-bind="src:picture" style="width:100px;height:100px" />
</div>
</div>
<div id="imageList" data-win-control="WinJS.UI.ListView" data-win-bind="winControl.itemDataSource:sportsImageList.dataSource" data-win-options="{itemTemplate:select('.myTemplate')}"></div>
</div>
</body>
</html>
I have tried many ways to bind the URL to the Image, but on the screen I can only see the links but not the actual images.
Where am I wrong?
All help and suggestions appreciated.
Thank you!
I believe your error is in your assignment line, remember that itemDataSource is a property of the ListView control. As it is in your code you're assigning that property to the imageList element.
Change it to this:
imageList.winControl.itemDataSource = sportsImageList.dataSource;
I would like to add a close button to close a panel that appears in the browser. For that I have a javascript file that launches the prompt.html file that is my panel.
var panel = require('sdk/panel').Panel({
width : 400,
height : 400,
contentURL : self.data.url('prompt.html')
});
Then in my prompt.html I have the following :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MyPanel</title>
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
<body class="din">
<h1>MyPanel</h1>
<div id="div1"></div>
<div id="div2"></div>
</body>
The script contains code to add nodes to the div and display a content. My question is : how can I add a button to close the panel ?
Add a button to your panel.
On click, self.port.emit some message telling your main.js code to hide the panel.
Upon receiving the message, call panel.hide().
Working example
main.js
var self = require("sdk/self");
var panel = require('sdk/panel').Panel({
width : 400,
height : 400,
contentURL : self.data.url('prompt.html'),
contentScriptFile: self.data.url('prompt.js')
});
// On "close" messages from the content script...
panel.port.on("close", function() {
console.log("asked to close");
// hide/close the panel.
panel.hide();
});
// Initially show the panel for testing purposes.
panel.show();
prompt.html
<!doctype html>
<html>
<head>
<title>MyPanel</title>
</head>
<body>
<div>
<a id="close_button">close</a>
</div>
<h1>MyPanel</h1>
<div id="div1">div1</div>
<div id="div2">div2</div>
</body>
</html>
prompt.js
// Wire-up an on click event listener.
document.getElementById("close_button").addEventListener("click", function() {
// Emit a "close" message to main.
self.port.emit("close");
});
This code attempts to dynamically switch the class of the StateContainer div from StateOne to StateTwo to alternate the visibility of the DIV.
When I run it, I always see the following both before and after clicking the button.
Visible first
Visible first
Visible first
Visible first
Would appreciate any suggestions for why this code does not work the way I'm expecting.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<style type="text/css">
.StateOne .InitiallyHidden { display: none; }
.StateTwo .InitiallyVisible { display: none; }
</style>
<script type="text/javascript">
$(document).ready(function()
{
$('.x').click(
var s = document.GetElementById('StateContainer');
s.className = (s.className == 'StateOne' ? 'StateTwo' : 'StateOne');
);
});
</script>
</head>
<body>
<button class="x">Change StateContainer</button>
<div class="StateOne" id="StateContainer">
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
</div>
</body>
</html>
It looks like you're not using the click event properly. You need to provide it with a function:
$('.x').click(function() {
var s = document.getElementById('StateContainer');
s.className = (s.className == 'StateOne' ? 'StateTwo' : 'StateOne');
});
Also, if you're already using jQuery, the following syntax is much shorter than document.getElementById (which doesn't have a capital G, by the way):
var s = $("#StateContainer")[0];
Steve