Javascript Running on JSFiddle but not on a webpage - javascript

Ok so I have a code that would show different forms based on dropdown selection
Here's the fiddle to that..
Well its always giving me Test1 which means its not changing the div display, it's working on JSFiddle but not on the webpage..
and here's my webpage markup
<html>
<body>
<style>
.hidden {
display: none;
}
</style>
<script type='text/javascript'>
document.getElementById('options').onchange = function() {
var i = 1;
var myDiv = document.getElementById(i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
</script>
<select name="options" id="options">
<option value="1"> Display </option>
<option value="2">Wka</option>
</select>
<div id="1" class="hidden" style="display: block">Test 1</div>
<div id="2" class="hidden">Test 2</div>
</body>
</html>

That is because in the fiddle your code is set to run at onLoad, but in your code its running before the DOM is created.
Wrap your code into a window.onload event like this:
window.onload = function()
{
document.getElementById('options').onchange = function() {
var i = 1;
var myDiv = document.getElementById(i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
};
Anyway, like #positivew remembered, your code misses the <head> tag. Is semantically correct to put your JS scripts inside it.

The best thing to do when such problem comes works in jsfiddle and not on webpage is to see the source of the fiddle page.
Your source of the fiddle appears as:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
.hidden
{
display: none;
}
</style>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
document.getElementById('options').onchange = function()
{
var i = 1;
var myDiv = document.getElementById(i);
while(myDiv)
{
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
}//]]>
</script>
</head>
<body>
<select name="options" id="options">
<option value="1"> Test1 </option>
<option value="2">Test2</option>
</select>
<div id="1" class="hidden" style="display: block">Test 1</div>
<div id="2" class="hidden">Test 2</div>
</body>
</html>
Paste the above code directly and it will work.
After pasting the code directly then you can remove unncecessary lines like below from the fiddle:
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">

You need a onload function so your code is run after your HTML is loaded. Try this:
window.onload = function () {
document.getElementById('options').onchange = function () {
var i = 1;
var myDiv = document.getElementById(i);
while (myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
}
You can also add the code after all your HTML, before the end of the body tag.
And note that in your post you are missing <head> tags.

You seem to be missing <head> tags.

Jsfiddle is running your script .onload of the window object, without you realizing it. This allows your script to pause on execution until the DOM is ready to be manipulated.
To have it work in your own environment, you can:
Place the entire script after the HTML you're trying to manipulate (e.g. end of the <body>)
Leave your code above the <body> and run it onload of the window object, e.g.
window.onload = function () {
document.getElementById('options').onchange = function () {
var i = 1;
var myDiv = document.getElementById(i);
while (myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
}

The page is loaded into the DOM from the top down.
Your document.getElementById('options').onchange is being called before the element with id options exists in the DOM.
If you put your script below the divs, it'll work because the divs are now there before the script is called.

Related

Toggle button : Javascript toggle doesn't works locally

I try to create a toggle button in order to show/hide some content. For the moment, I use that :
// test.js
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
#content {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<button id="toggle">Click Me</button>
<div id="content">Hello World</div>
</body>
</html>
If I use these code with codepen or JSFiddle, all works fine, but when I try it locally, ( when I click on my index.html file, open it with firefox or an other browser ) my button "Click Me" doesn't works.
When I click on it, nothing happens...
Someone to show me why ?
You could make your function to be fired on load event.
Possible example
(function() {
var loadedContent = {
init: function() {
window.addEventListener("load", function(event) {
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ?
"block" :
"none";
});
});
}
};
loadedContent.init();
})();
#content {
display: none;
}
<button id="toggle">Click Me</button>
<div id="content">Hello World</div>

HTML Trouble putting in JS

I have a document where it goes like this:
<!DOCTYPE html>
<html>
<head>
<!-- some title, meta stuff and css -->
</head>
<body>
<style src="/secondvid.js"></style>
<div id="vid1"></div>
<button onclick="showSecondVid('vid1', 'vid2');">Video 2</button>
<div id="vid2" style="display: none;"></div>
</body>
</html>
What is inside the divs is not important, but the script looks like this:
function showSecondVid(vid1Id, vid2Id) {
document.getElementById(vid1Id).style.display = "none";
document.getElementById(vid2Id).style.display = "block";
document.querySelectorAll('button')[0].style.display = "none";
dayUp();
}
function dayUp() {
if (localStorage.dayFinished === 4) {
localStorage.dayFinished = 0;
} else if (localStorage.dayFinished) {
localStorage.dayFinished++;
}
}
When I click the button, nothing happens. Can someone help?
I want the first div to disappear and the second one to appear.
Try to call your script like this :
<script src="/secondvid.js"></script>
instead of
<style src="/secondvid.js"></style>

Changing border in Javascript

I have been learning Javascript and I'm a little confused as to why this doesn't work. I'd like it so if you click the div, it creates a red border around it:
JSFiddle link
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Generation X</title>
</head>
<body>
<script src="test.js"></script>
<div id="clickHere" onclick="run()">
<p>Hello</p>
</div>
</body>
</html>
Javascript:
function run() {
document.getElementById("clickHere").style.border = thick solid red;
alert("Changed");
}
make it ..updated fiddle (you need to wrap it in the head tag)
function run(thisObj) {
thisObj.style.border = "1px solid red"; //or "1px solid #ff000"
alert("Changed");
}
also, rather than getting the reference to element again, simply pass the reference during the time of invocation.
So, instead of putting an onClick on div, use a addEventListener should be better.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Event_attributes
https://jsfiddle.net/5jsbhbhu/5/
var run = function() {
document.getElementById("clickHere").style.borderColor = "red";
document.getElementById("clickHere").style.borderWidth = "1px";
document.getElementById("clickHere").style.borderStyle = "solid";
alert("Changed");
};
var node = document.getElementById('clickHere');
node.addEventListener('click', run);

Jquery Need Help - Changing content when clicking on a link

I need help. I'm trying to get a link to change the displayed answer when you click on the link. I want it to toggle back and forth each time you click on it. I've been playing around with multiple items but nothing seems to work yet. I've commented out some notes to help sort out what I want to do. Thanks!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<script src="jquery.js" type="text/javascript" language="JavaScript"></script>
<script type="text/javascript">
function flipSwitch(){
document.getElementById('first').style.display = 'block';
document.getElementById('second').style.display = 'block';
//get the first div into this variable
//var firstDiv = document.getElementById('first');
firstDiv.style
//change it's style/display properties from none to block. Is it visible now when you click the link?
//firstDiv.
}
</script>
</HEAD>
<BODY>
<div id="home">
Let's see if we can get this to work?
</div>
<div id="first" style="DISPLAY: none;">This is a test...</div>
<div id="second" style="DISPLAY: none;">of the emergency broadcast system</div>
</BODY>
It's good practice to move javascript out of your HTML.
Here is an example of toggling the CSS Display property in javascript.
Fiddle: http://jsfiddle.net/LdPfS/
var link = document.querySelector("#home > a")
link.addEventListener("click", function(e) {
e.preventDefault()
var firstDiv = document.getElementById('first'),
secondDiv = document.getElementById('second'),
toggle = firstDiv.style.display === "none" ? "block" : "none"
/* toggle = firstDiv.style.display === "none" ? "block" : "none"
* Read as
* if ( firstDiv.style.display === "none" ) {
* toggle = "block"
* else {
* toggle = "none"
* }
*/
firstDiv.style.display = toggle
secondDiv.style.display = toggle
})
I agree that the all caps html is weird but for the sake of making this quick, I'll copy/paste your code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<script src="jquery.js" type="text/javascript" language="JavaScript"></script>
<script type="text/javascript">
function flipSwitch(){
// first and foremost, you're using jQuery so let's use jquery
if ($('#first').is(':hidden')) {
$('#first').show();
$('#second').hide();
} else {
$('#first').hide();
$('#second').show();
}
}
// next, let's get your javascript OUT of the html
$(document).ready(function () {
// when the document has loaded, attach our function as a
// click handler to the link
$('#my_switch').on('click', flipSwitch);
});
</script>
</HEAD>
<BODY>
<div id="home">
<a id="my_switch">Let's see if we can get this to work?</a>
</div>
<div id="first" style="DISPLAY: none;">This is a test...</div>
<div id="second" style="DISPLAY: none;">of the emergency broadcast system</div>
</BODY>
Similar to MBottens, but with some simple JQuery:
$('#home > a').on('click', function(e) {
e.preventDefault()
$('#first').toggle();
$('#second').toggle();
});
Try this logic. Take a global variable and set its value to 1.
<script type="text/javascript">
var countClick=1;
function flipSwitch(){
if(countClick%2==0){
document.getElementById('first').style.display = 'block';
document.getElementById('second').style.display = 'none';
}
else{
document.getElementById('first').style.display = 'none';
document.getElementById('second').style.display = 'block';
}
countClick++;
}
</script>
Also please change your html with the following html:
<body>
<div id="home">
Let's see if we can get this to work?
</div>
<div id="first" style="display: none;">This is a test...</div>
<div id="second" style="display: none;">of the emergency broadcast system</div>
</body>

Glassbox.js javascript plugin doesn't work in JQuery

So I have the following code, and glassLoad() does NOT work when called from a JQuery context. I have isolated the problem to one specific line, myBox.apos('170px', '150px'); which seems to stop the entire function from running, but ONLY when called from JQuery. If I use a standard onclick="glassLoad();" it runs the function perfectly, but if i include the function in JQuery it stops the WHOLE JQuery function from running:
#model IEnumerable<OneEightyWebApp.Models.PropertyDB>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
<script src="../../Content/javascripts/glassbox/glassbox.js" type="text/javascript"></script>
<head>
<title></title>
<script type="text/javascript">
function populate() {
var select = document.getElementById("centres");
for (var i = 1; i <= 10; i++) {
var option = document.createElement("option");
option.value = i;
option.text = i;
select.appendChild(option);
}
}
function divGenerator() {
var div;
for (var i = 1; i <= document.getElementById("revisions").value; i++) {
div = document.createElement("div");
div.className = "class1";
div.innerHTML = "Space " + i;
div.style.width = "100px";
div.style.height = "100px";
div.style.float = "left";
document.getElementById("container2").appendChild(div);
}
}
function glassLoad() {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('myBox', '128px', '62px', 'hidden');
myBox.apos('170px', '150px');
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", ".class1", function () {
glassLoad();
alert("div clicked");
});
});
</script>
</head>
<body>
<!--
popup
-->
<div id="container1" style="width: auto; height: 50px;">
<button style="margin: auto; vertical-align: top; float: left; font-size: 16px;" type="button" onclick="divGenerator();">Generate</button>
#Html.DropDownList("revisions", (List<SelectListItem>)ViewData["revisions"])
</div>
<div id="container2" style="margin: 10px; float: left;"></div>
<div id="myBox">Hello!</div>
</body>
To make this run with PrototypeJS
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"> </script>
<script type="text/javascript">
document.observe('dom:loaded',function(){
$$("body")[0].on('click', ".class1", function () {
glassLoad();
alert("div clicked");
});
});
</script>
This will trigger when the DOM is loaded and uses the CSS selector method $$() and selects the first element in the list that is returned and then attaches to the click event of that element.
The rest of your javascript doesn't look like it depends on jQuery or Prototype so you should be able to swap this code snippet into your code.
It appears Glassbox.js does not support jQuery. It is built to work with Prototype, which is an alternative framework. So you'll have to either use Prototype instead or find an alternative plugin.

Categories