javascript dynamic content with select long running script - javascript

Basically been trying to figure out some javascript stuff, so was making a couple of divs, and a select, so depending on the selected option, depends on what div is shown/hidden.
It seems to work ok, hiding all but the first div after loading, then when the second option is selected, it shows the second div, hiding the first by appending a class.
When I change the option back to the first div though, it creates a long running script that jams everything up and I can't figure out where the long running script comes from.
Any advice appreciated.
Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.itemCont.show{
display:block;
}
.itemCont.hide{
display:none;
}
</style>
</head>
<body onload="sortDivs();">
<select name="options" id="opts" onchange="optSelect(this);">
<option value="0">item</option>
<option value="1">another</option>
</select>
<div class="output">
<div class="itemCont show" id="div0">
<h1>1</h1>
</div>
<div class="itemCont" id="div1">
<h1>2</h1>
</div>
</div>
</body>
<script async="async" ype="text/javascript">
function sortDivs(){
var divs = document.getElementsByClassName('itemCont');
for( var i = 0; i < divs.length; i++ ){
if(i>0){
divs[i].className += ' hide';
}
}
}
function optSelect(opt){
var val = opt.value;
var divs = document.getElementsByClassName('itemCont');
var divActive = document.getElementsByClassName("itemCont show");
divActive[0].className = divActive[0].className.replace(/\bshow\b/,'hide');
for ( var i = 0; i < divs.length; i++ ) {
if(i = val){
divs[i].className = divs[i].className.replace(/\bhide\b/,'show');
}
}
}
</script>
</html>

You have a typo = should be ==
for ( var i = 0; i < divs.length; i++ ) {
if(i == val){
divs[i].className = divs[i].className.replace(/\bhide\b/,'show');
}
}
I recommend using jQuery (toggle) to handle this kind of stuff though :)

Related

loading view via java-script

i have a main html page (index.html)
<body>
<script type="text/javascript">
function active(el) {
var sections = document.querySelectorAll('.sidebar>li');
for (i = 0; i < sections.length; i++) {
sections[i].classList.remove('current');
}
el.classList.add('current');
}
</script>
<h1 onclick="active(this); load('content','pages/home.html')" class="sidebar-title">GOSSAMER LAN</h1>
<ul class="sidebar">
<li onclick="active(this); load('content','pages/network.html')">
<h2>Network settings</h2>
<small>Edit configuration</small>
</li>
</ul>
</section>
<section id="content"></section>
</section>
<script type="text/javascript" src="js/main.js"></script>
</body>
and network setting view (network.html) that has a button
<div class="save-button" onclick="validation();">Save changes</div>
what i want to do is on clicking the button to return to view (home.html)
function validation() {
var inputs = document.querySelectorAll('input[type=text],input[type=password]');
var input = [];
for (p = 0; p < inputs.length; p++) {
input.push(inputs[p].value);
if (!inputs[p].parentNode.classList.contains("deactive")) {
inputs[p].value == "" ? inputs[p].classList.add("error") : inputs[p].classList.remove("error")
}
}
if (input.indexOf("") == -1) {
sendData();
load("content","pages/home.html");
}
via my java script code
function load(page,src) {
console.log( document.getElementById(page));
document.getElementById(page).innerHTML='<object type="text/html" id="dynamic-'+page+'" data="'+src+'" style="width:100%; height: 100%;" ></object>';
}
load("content","pages/home.html");
i have put most of my code to make it kind of detailed as to what i hope to achieve i am getting Cannot set property 'innerHTML' of null when executing the onclick function (validation)
please any help ?
thank you

add div using appendChild

This code is supposed to be looping and adding multiple divs, but it isn't working. When I click it, only one div appears. If I click again, nothing happens.
<body>
<div class="start" >
<div id = "coba">
</div>
<div id = "cobi">
</div>
</div>
<script>
var divs = document.getElementById("coba").addEventListener("click", function () {
for (var i = 1; i < 100; i++) {
var di = document.createElement('div');
document.getElementById('coba').appendChild(di);
}
});
</script>
</body>
Thanks for your help
Your code does not work because you did not do anything with the variable "i" in the for statement. If you look at the fiddles of user2181397 & meghan Armes you will see how they added a line in the script to put it to work.
I tested the below in my IDE and it works just fine:
<body>
<div class="start" style="margin-top:50px; color:black;">
<div id = "coba">
<p>Click Me</p>
</div>
<div id = "cobi">
</div>
</div>
<script>
var divs = document.getElementById("coba").addEventListener("click", function() {
for (var i = 1; i < 100; i++) {
var di = document.createElement('div');
di.innerHTML=i;
document.getElementById('coba').appendChild(di);
}
});
</script>
</body>

javascript for is not working

First time trying javascript and i cant find a solution about this.
I need a open/close div button.
if div1 is not visible and i press button 1
set it visible
set all other not visible
elseif div1 is visible and i press button 1
set it not visible
this is my code so far...
<script type="text/javascript">
function toggle_visibility(id)
{
if (document.getElementById(id).style.display=='block')
{
document.getElementById(id).style.display='none';
}
else
{
document.getElementById(id).style.display='block';
for (i=0; i<5; i++)
{
document.getElementById(i).style.display='none';
}
}
}
</script>
<button onclick="toggle_visibility(1);">
1
</button>
...
<button onclick="toggle_visibility(5);">
5
</button>
i forgot this ->
<div id="1" style="display:none">
1
</div>
...
<div id="5" style="display:none">
5
</div>
You have no element with a id. And a id must not begin with an number (in (X)HTML, but not HTML5)! If you just want to show one element try my showOnly function.
<script type="text/javascript">
function toggle_visibility(id)
{
var i; // omiting this causes a global variable
if (document.getElementById("a"+id).style.display=='block')
{
document.getElementById("a"+id).style.display='none';
}
else
{
document.getElementById("a"+id).style.display='block';
for (i=1; i<=5; i++)
{
document.getElementById("a"+i).style.display='none';
}
}
}
function showOnly(id) {
for(var i=1; i<=5; i++) {
document.getElementById("a"+i).style.display='none';
}
document.getElementById("a"+id).style.display='block';
}
</script>
<div id="a1" onclick="toggle_visibility(1);">1</div>
<!-- ... -->
<div id="a5" onclick="toggle_visibility(5);">5</div>
See also this fiddle.
You're missing the ID attribute from your div's.
<div id="yourId">
Ideally the ID shouldn't start with a number.
In addition you can use the browser console window to help identify such problems.

Two similar javascript functions, one works, the other doesnt, why?

I am a Javascript beginner, I am trying to get some simple code working. I added one snippet as a check to make sure Javascript is working in the page, which it does. It just changes a bit of text from blue to red.
The second piece of code is supposed to hide a <div>, or show it depending on the selected value. It does not work can somebody point me in the right direction? Thanks for any advice.
<!DOCTYPE html>
<html>
<head>
<title>getElementById example</title>
<script>
function changeColor(newColor) {
var elem = document.getElementById("para1");
elem.style.color = newColor;
}
</script>
<script>
// EXPAND
function Hide(elementid){
document.getElementById(elementid).style.display = 'none';
}
function Show(elementid){
document.getElementById(elementid).style.display = '';
}
</script>
</head>
<body>
<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
<div id="one">ONE</div>
<div id="two">TWO</div>
<select>
<Option value="javascript:Show('one');javascript:Hide('two')">one</option>
<Option value="javascript:Hide('one');javascript:Show('two')">two</option>
</select>
</body>
</html>
The value attribute does not run JavaScript.
You need to bind a change event to the select element, and then look at the selected value to determine which one to show or hide.
For example:
<div id="one">ONE</div>
<div id="two">TWO</div>
<div id="three">THREE</div>
<select>
<option>one
<option>two
<option>three
</select>
<script>
function show(id) {
document.getElementById(id).style.display = '';
}
function hide(id) {
document.getElementById(id).style.display = 'none';
}
function whichDiv(event) {
var select = event.target;
var options = select.options;
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.selected) {
show(option.value);
} else {
hide(option.value);
}
}
}
document.querySelector('select').addEventListener('change', whichDiv);
</script>
I think you should use block : document.getElementById(elementid).style.display = 'block';

Using JQuery how to show and hide different div's onClick event

I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
Code Follows:
<div class="toggle_button">
Toggle
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
Jquery Code :
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
The above code shows all divs on first click itself but it should show div1 on first click as mentioned.
I'll try my shot.
EDIT:
After second though, to avoid global variable use it's better to do the following
$(document).ready(function() {
$("#toggle_value").click((function(){
var counter = 0;
return function()
{
$("#div" + counter).hide("fast");
counter = (counter % 3) + 1;
$("#div" + counter).show("fast");
}
})());
});
You should add a counter in the function.
$(document).ready(function() {
var count = 0;
$("#toggle_value").click(function(){
if (count == 0) {
$("#div1").show("fast");
$('#div2').hide();
count++;
}
else if (count == 1) {
$("#div2").show("fast");
...
count++;
}
else if (count == 2) {
$("#div3").show("fast");
....
count++;
}
else {
$('div').hide();
count=0;
}
});
});
How about this
Working Example here - add /edit to URL to edit the code
$('html').addClass('js'); // prevent hiding divs on DOM ready from 'flashing'
$(function() {
var counter = 1;
$('#toggle_value').click(function() {
$('div','#container')
// to stop current animations - clicking really fast could originally
// cause more than one div to show
.stop()
// hide all divs in the container
.hide()
// filter to only the div in question
.filter( function() { return this.id.match('div' + counter); })
// show the div
.show('fast');
// increment counter or reset to 1 if counter equals 3
counter == 3? counter = 1 : counter++;
// prevent default anchor click event
return false;
});
});
and HTML
<!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" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Div Example</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; }
.display { width:300px; height:200px; border: 2px solid #000; }
.js .display { display:none; }
</style>
</head>
<body>
<div class="toggle_button">
Toggle
</div>
<br/>
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
div1
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
<div>
</body>
</html>
This could easily be wrapped up in a plugin
A simple way would be to introduce a variable that tracked clicks, so something like this:
var tracker = 0;
$(document).ready(function() {
$("#toggle_value").click(function(){
if(tracker == 0)
{
$("#div1").show("fast");
}else if(tracker ==1)
etc etc
tracker ++;
});
});
My solution is a little different - I'd do it dependant on the state of the divs at the current time (on click). See below for what I mean by this.
$(document).ready(function() {
$("#toggle_value").click(function(){
if ($("#div1).is(':visible')) { // Second click
// Hide all divs and show d2
$("#div1").hide();
$("#div2").show("fast");
$("#div3").hide();
$("#div4").hide();
} else if ($("#div2").is(':visible')) { // Third click
// follow above example for hiding all and showing div3
} else if ($("#div3").is(':visible')) { // Fouth click
// follow above example for hiding all and showing div1
} else { // first click
// All divs should be hidden first. Show div1 only.
$("#div1").show("fast");
}
});
});
Just to warn you - I have not tested this code :)
Based upon the following for determining visibility: http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_determine_the_state_of_a_toggled_element.3F
Hope it helps
I prefer to use "filter" method and make a little easier work with counter:
(function () {
var divCounter = 0, divs;
$(function () {
divs = $('#div1, #div2, #div3');
$('#toggle_value').click(function (e) {
divs.hide() // hide other divs
.filter(function (index) { return index == divCounter % 3; }) // select appropriate div
.show('fast'); // and show it
divCounter++;
});
});
})();
I would probably do something like: (The following assumes all your <div>s are in a container with id "container")
$(document).ready(function() {
var $allDivs = $("#container > div");
var counter = 0;
$("#container > div").click(function(){
counter = counter < $allDivs.length - 1 ? counter + 1 : 0;
$allDivs.not(":eq("+counter +")").hide("fast");
$allDivs.eq(counter).show("fast");
});
});
The .toggle function in jQuery takes any number of argument functions, so the problem is already solved. See the docs under Events.
$("#toggle_value").click(function()
{
$("#div" + (++c) % 3).show().siblings().hide();
}
var c = 1;
$("#toggle_value").click(function()
{
$("#div" + c).hide("fast");
$("#div" + ++c).show("fast");
if (c > 3) c=1;
});
First You have to add query basic file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
Then you have to add the following code:
<script type="text/javascript">
$(document).ready(function () {
$("#hide").click(function(){
$(".slider_area").hide(1000);
$("#show").css("display","block");
$("#hide").css("display","none");
});
$("#show").click(function(){
$(".slider_area").show(1000);
$("#show").css("display","none");
$("#hide").css("display","block");
});
});
</script>
Add the code above into the header portion and the code below in the body portion.
<img src="images/hide-banner.png" id="hide" class="link right"/>
<img src="images/show-banner.png" id="show" class="link right dis" />
The code is ready for the different image click for show and hide div.
<div id="div_<%=id>">
</div>
<div id="Hide_<%=id>" style="display:none;">
</div>
<div id="div_<%=id>">
</div>
<div id="Hide_<%=id>" style="display:none;">
</div>
<div id="div_<%=id>">
</div>
<div id="Hide_<%=id>" style="display:none;">
</div>
<div id="div_<%=id>">
</div>
<div id="Hide_<%=id>" style="display:none;">
</div>
<script>
var temp = 0;
var temp1 = 0;
$("#div_<%=id>").click(function(){
if (temp1 == 0) {
$('#' + temp).hide();
temp = 'Hide_<%=id>';
$('#Hide_<%=id>').show();
temp1 = 1;
}
else{
$('#' + temp).hide();
temp = 'Hide_<%=id>';
$('#Hide_<%=id>').show();
temp1 = 0;
}
});
</script>

Categories

Resources