Jquery Need Help - Changing content when clicking on a link - javascript

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>

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>

Insert HTML dynamically based on CSS class with Javascript

With the use of Javascript I want to display different HTML content based on the value of a class of an HTML element which is existing on the page. eg:
<body class="de">
display:
<div id="de">some html</div>
If the body element has another class value, eg class="en" it should display
<div id="en">some other html</div>
I have already played around with hasClass function and an if statement. But it did not work for me.
What about ?
<body class="en">
<script>
if($('body').hasClass('de')) {
$('body').html('<div id="de">some html</div>');
}
else if($('body').hasClass('en')) {
$('body').html('<div id="en">some other html</div>');
}
else if($('body').hasClass('es')) {
$('body').html('<div id="es">another html</div>');
}
else {
...
}
</script>
Dynamic :
var bodyClass = $('body').attr("class");
var bodyValue = $('#' + bodyClass).html();
$('body').html(bodyValue);
But you should verify that body has a class and that an element with an identical id exist in your document.
The solution I am working with:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body class="lang-de some other">
<h1>Überschrift 1</h1>
<div id="lang"></div>
<script>
var bodyClass = $('body').attr("class").substr(0,7);
var bodyValue = $('#' + bodyClass).html();
$('body').html(bodyValue);
if($('body').hasClass('lang-de')) {
document.getElementById("lang"); {
$('#lang').html('<div id="de">some html</div>');}
}
else if ($('body').hasClass('lang-en')) {
document.getElementById("lang"); {
$('#lang').html('<div id="en">some other html</div>');}
}
</script>
</body>
</html>
With jQuery :
$('.de').html('<div id="de">some html</div>');
If you have different tags to fulfil with different html content use a generic class + a specific one (eg : class="dynamic de") and loop all elements with "dynamic" class and use hasClass in a if/elseif (or better a switch/case) to target them separatly.
Btw, AngularJs has "directives" that handle perfectly that kind of need ;)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body class="lang-de some other">
<h1>Überschrift 1</h1>
<div id="lang-de"></div>
<div id="lang-en"></div>
<script>
var bodyClass = $('body').attr("class").substr(0,7);
$('div#lang-*').hide();
$('#' + bodyClass).show();
</script>
</body>
</html>
What about?
<html>
<head>
<style>
body.lang-en #en{display:block;}
body.lang-de #de{display:block;}
</style>
</head>
<body class="lang-en">
<div id="en" hidden>some text</div>
<div id="de" hidden>some other text</div>
<hr>
<button onclick="toggle()"></button>
</body>
<script>
function toggle(){
var lang=['lang-en','lang-de'];
var i=lang.indexOf(document.body.className);
document.body.className=(i+1 == lang.length ? 0 :i+1);
}
</script>
</html>
OR
with jQuery
$('#en,#de,#jp').hide();
$('#'+$('body').attr('class').replace('lang-','')).show();

Javascript Running on JSFiddle but not on a webpage

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.

jQuery .insertAfter() copying input field values

I have created a html webpage here:
http://diagrams.inse1d.info/wbt.html
Code:
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div id="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" id="wbtTitle" /></h1>
<div id="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" id="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
Here is the jQuery code I wrote:
$(document).ready(function() {
$("h1").keypress(function(e) {
//get
wbtTitle = $('#wbtTitle').val();
// Write text after enter
if (e.which == 13) {
$("h1").text(wbtTitle);
}
});
$("span").keypress(function(e) {
//get
wbtNote = $('#wbtNote').val();
// Write note after enter
if (e.which == 13) {
$("span").text(wbtNote);
}
});
//Insert new WBT on button click
$("button").each(function() {
$(this).click(function() {
var wbtSet = $( "article" ).html();
$(wbtSet).insertAfter('section');
});
});
});
What I want to do is set the title and some note text using input boxes which works using jQuery. I then want to add a copy of the html into another article when the button is pressed without copying the inputs previously made with the possibility of setting new values when the article is cloned. The process should repeat over and over again.
Here is an image to help explain:
I am quite new to jQuery, I think you need to use a loop to fix this, I read that a .each() can be used http://api.jquery.com/jQuery.each/ but not quite sure.
Any help will be appreciated. Thanks.
I think I got your answer.
I changed the html a bit, because you duplicated some id's with your approach, that's not good. id's have to be unique on a page. I simply changed them to classes.
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div class="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" class="wbtTitle" /></h1>
<div class="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" class="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
And of course the jQuery. I got rid of your first two functions because they had no purpose in this context.
$(document).ready(function() {
//Insert new WBT on button click
$("button").on('click', function() {
var title = $(this).prev().find('.wbtTitle').val();
var note = $(this).prev().find('.wbtNote').val();
var wbtSet = $(this).prev("section").html();
$(this).prev().find('.wbtTitle').replaceWith(title);
$(this).prev().find('.wbtNote').replaceWith(note);
$(this).prev("section").after('<section>' + wbtSet + '</section>');
});
});
Here is a working fiddel
Fixing the answer given by hitokun_s
window.onload = function() {
// Save a copy of the element wbtSet element on pageload
var wbtSet = $("article").clone();
$("button").each(function() {
$(this).click(function() {
// Append a new one to the holder of the wbSets
$(wbtSet).appendTo($('section'));
});
});
}
I think this is what you want to do.
window.onload = function() {
$("button").each(function() {
$(this).click(function() {
var wbtSet = $("article:first-child").clone();
wbtSet.find("input").val("");
$(wbtSet).appendTo($('section'));
});
});
}

Categories