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.
Related
Brief synopsis of what I am doing: As of now I am trying to build a 6 x 6 grid and get some sign of life when I click on any of the grid boxes.
The result I want for now, is by clicking in any of the boxes I get a console message saying a piece was picked.
My main goal is to be able to differentiate between which box I picked, but first I need to figure it out generally.
HTML:
<div class="container">
<div class="row">
<div class="btn btn-lg btn-success col-lg-offset-4 col-md-4" id="makeBoard">Generate Board</div>
</div>
<div id="spacer"></div>
<div class="row">
<div class="col-md-12" id="newBoard"></div>
</div>
</div>
JQuery:
$(function(){
$('#makeBoard').click(function() {
var boardSize = 6;
makeBoard(boardSize);
});
function makeBoard(boardSize){
for(i = 0; i < boardSize; i++){
$('#newBoard').append("<div class='row' id='row"+i+"'>");
var row = "#row"+i;
for(j = 0; j < boardSize; j++){
var content = "<div class='col-md-2 boardPiece' id='"+i+"_"+j+"'></div>";
$(row).append(content);
}
$('#newBoard').append("</div>");
}
}
$('div.boardPiece').click(function() {
console.log("You clicked a piece!");
});
});
I double checked the html output by inspecting the element and indeed all the squares have the class 'boardPiece' but whenever I click on anywhere in the grid nothing gets logged in the console.
However, I have tried to console log the id 'newBoard' by clicking anywhere in the box and that worked. I'm assuming it has something to do with the boardPiece not being hardcoded in using HTML like newBoard is?
I'm using JS/JQuery so I can eventually change the board size from a form.
Thank you in advance.
Edit (Answer Below)
//Changed from this
$('div.boardPiece').click(function() {
console.log("You clicked a piece!");
});
//To this
$('.row').on("click", "div.boardPiece", function() {
console.log("You clicked a piece!");
});
Hello everybody I would like to hide some divs and display others when I click on a specifiks links.
Actually I did like this :
<html>
<head>
<script>
function loadA(){
document.getElementById("A").style.display="block";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
}
function loadB(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="block";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
}
function loadC(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="block";
document.getElementById("D").style.display="none";
}
function loadD(){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="block";
}
</script>
</head>
<body>
<div class="menu">
A
B
C
D
</div>
</body>
</html>
This is work with me but as you see it's not a good practice and sure there is another way better than this , can you show me please !
A solution without javascript:
.container > div{
display:none
}
.container > div:target{
display:block
}
<div class="menu">
<a href="#A" >A</a>
<a href="#B" >B</a>
<a href="#C" >C</a>
<a href="#D" >D</a>
</div>
<div class="container">
<div id="A" >A content</div>
<div id="B" >B content</div>
<div id="C" >C content</div>
<div id="D" >D content</div>
</div>
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Atarget
https://css-tricks.com/css3-tabs/
You can create one function and reuse it for each element:
function loadDiv(id){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
document.getElementById(id).style.display="block";
}
And pass the correct id into each onclick:
<div class="menu">
A
B
C
D
</div>
Here's how you should do it. No inline javascript, handling click events with an eventListener and wrapping all elements together with a class, making it much less code to write and maintain:
JS:
function divLoader(e){
var hide = document.getElementsByClassName("hideAndShow");
for (var i = 0; i<hide.length;i++) {
hide[i].style.display="none";
}
document.getElementById(e.target.getAttribute('data-link')).style.display="block";
}
var anchors = document.querySelectorAll('.menu > a');
for (var i = 0; i<anchors.length; i++) {
anchors[i].addEventListener('click',divLoader);
}
HTML:
<div class="menu">
A
B
C
D
</div>
<div id="A" class="hideAndShow" style="display:none;">A</div>
<div id="B" class="hideAndShow" style="display:none;">B</div>
<div id="C" class="hideAndShow" style="display:none;">C</div>
<div id="D" class="hideAndShow" style="display:none;">D</div>
In such cases where you have similar repetitive code you can use a common technique called "Abstraction". The main idea is the turn the common code into parameters of a single function in your case it would be:
function loadByID(id){
document.getElementById("A").style.display="none";
document.getElementById("B").style.display="none";
document.getElementById("C").style.display="none";
document.getElementById("D").style.display="none";
document.getElementById(id).style.display="block";
}
However this is also still a little bit redundant, for larger menus and displaying multiple links you can do something like
function loadByIDs(ids){
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
document.getElementById(links[i].id).style.display = none;
}
for each(var id in ids){
document.getElementById(id).style.display = block;
}
}
This will work much better when you have too much links and want to display more than one link at a time (so you will need to pass in an array)
Note: If you are using Jquery you can just use .each() function to get rid of the first for loop
Hope this helps!
I think the best practice in your case is to define a general function that work however the number of links with specific class in my example the class is link, take a look at Working Fiddle.
Now your script will work with dynamic links added in div, you have just to add html without touching the js will detect change.
HTML :
<div class="menu">
A
B
C
D
</div>
JS :
load = function(e){
//select all links
var links = document.getElementsByClassName('link');
//Hide all the links
for (i = 0; i < links.length; i++) {
links[i].style.display = "none";
}
//Show clicked link
e.target.style.display = "block";
}
Hope this make sens.
HTML
<body>
<div id="main">
<ul id="nav">
<li>Home</li>
<li>About Us</li>
</ul>
<div id="container">
<div id="wrapper">
<div class="content">
<div id="menu_home">
<h2>Menu 1</h2>
</div>
<div id="menu_about">
<h2>Menu 2</h2>
</div>
</div><!--content-->
</div><!--wrapper-->
</div><!--container-->
</div><!-- main-->
</body>
JS
$(document).ready(function(){
$("#menu_home").slideUp("fast");
$("#menu_about").slideUp("fast");
$("#menu_home").show();
$("#nav a").click(function(){
var id = $(this).attr('id');
id = id.split('_');
$(".content div").slideUp("fast");;
$(".content #menu_"+id[1]).slideToggle("fast");
});
});
Here is the example
function loadA()
{
document.getElementById("A").style.visiblity="show";
document.getElementById("B").style.visiblity="hide";
document.getElementById("C").style.visiblity="hide";
document.getElementById("D").style.visiblity="hide";
}
if visibility dont work,just change the visibility keyword with visible and hide with hidden.
and one more thing,u should not write function for each div..what can u do just pass id of a div which u want to show and hide others..see below
function trigger(id)
{
var alldiv={"A","B","C","D"};
for(i=0;i<alldiv.length;i++)
{
if(alldiv[i]==id)
document.getElementById(id).style.visiblity="show";
else
document.getElementById(alldiv[i]).style.visiblity="hide";
}
}
In html I am having the following tags:
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
On Clicking on 2011-2012 or on 2012-2013 I want to set display property of div tag.
I am using the following Javascript code for this and I am calling the Javascript function in body tag. The output is showing style and display is not an object or property.
<script language="javascript">
function clickHnadler()
{
var xid= document.getElementsByTagName("span");
var xsp= xid[0].id;
alert("Span id is "+xsp);
if(xsp.charAt(0)=="M")
{
var oC = document.all("C"& xsp.substring(1,2));
if(oC.STYLE.display == "none")
{
oC.Style.Display = "";
}
else{
oC.Style.Display = "none";
}
}
}
</script>
use jquery:
you can pass in the function the element or the Id:
ex:
<span id=M26>2011-2012</span>
function clickHnadler(element)
{
var id = $(element > span).attr(id);
id[0] = 'c'; //not the nicest way, maybe use a replace or something like that
$(id).show(); //or $(id).css('display','list');
}
You may use clickHandler has following way,
function clickHandler(e) {
window.document.links[0].handleEvent(e);
}
You need to bind event spacifically to elements you want to handle click for. for more information please refer following link,
http://docs.oracle.com/cd/E19957-01/816-6409-10/evnt.htm#1009606
Based on what i understand from your question, I come up with this.
<script type="text/javascript" src="jquery1.8.js"></script>
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
2011-2012 details</div>
<br />
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
2012-2013 details
</div>
my page is full of php-generated content split in div's that have the same class but no id's. I want to show some buttons that allow me to manage, change and delete the div's; the buttons should be able to change the class, delete the div and select the content of the div.
How can I do this? is there a way to set the button's onclick action to something, say ... onclick="changetheclass(this)" that would actually change the class of the div containing this button?
Man I feel I'm not making any sense here :(
Did anyone understand what I'm talking about? If so, is there any possibility to do this?
Thanks in advance!
:)
EDIT: this is one of the divs, so that you could understand what I'm talking about:
<div class="box"><p>
this is the content of the div
<button onclick="change_the_class(this_div_or_something)">click here to change the class of the div</a>
<button onclick="select_the_content(this_div_or_something)">click here to change the class of the div</a>
<button onclick="delete_the_whole_div(this_div_or_something)">click here to change the class of the div</a>
</p></div>
Is this what you looking for ??
<html>
<head>
<script type="text/javascript">
function changeClass(elm) {
elm.parentNode.className ='newcss';
}
function deleteDiv(elm) {
var par = elm.parentNode;
var gran = par.parentNode;
gran.removeChild(par);
}
</script>
</head>
<body>
<div class='test'>
Hello
<button onclick="javascript:changeClass(this);" value="Change CSS">CSS</button>
<button onclick="javascript:deleteDiv(this);" value="Change CSS">Delete</button>
</div>
<div class='test'>
Hello
<button onclick="javascript:changeClass(this);" value="Change CSS">CSS</button>
<button onclick="javascript:deleteDiv(this);" value="Change CSS">Delete</button>
</div>
<div class='test'>
Hello
<button onclick="javascript:changeClass(this);" value="Change CSS">CSS</button>
<button onclick="javascript:deleteDiv(this);" value="Change CSS">Delete</button>
</div>
<div class='test'>
Hello
<button onclick="javascript:changeClass(this);" value="Change CSS">CSS</button>
<button onclick="javascript:deleteDiv(this);" value="Change CSS">Delete</button>
</div>
</body>
</html>
in JS, you can use querySelectorAll:
//get all divs with class "myDiv"
var divs = document.querySelectorAll('div.myDiv');
//for each of the gathered divs, do something with it
for(var i=0; i< divs.length;i++){
var aDiv = divs[i];
//"aDiv" is a div in the collection of matched divs
//you can do anything with it: add buttons etc.
}
First stay away from onclick="something" - inline JavaScript. then yes you can still manage to do what you want to do without ids.
var divs = document.getElementsByTagName('div'),
result = [],
len = divs.length,
i = 0,
aLink;
for(; i < len; i++){
// update the condition if there can be more than one class name as this assume a single class name
if (divs[i].className == 'myClassName') result.push(divs[i]);
}
len = result.length;
i = 0;
for (; i < len; i++) {
aLink = document.createElement('a');
aLink.innerHTML = 'Edit';
aLink._parent = result[i]; // store a reference to the parent div
aLink.href = '#';
aLink.onclick = function(ev) {
ev.preventDefault();
// do your edit stuff here, ev.target._parent contain the targetted div
};
result[i].appendChild(aLink);
}
$('div.my-class').each( function( index, element ){
var div = $( element ); // not sure if this is needed
// add the buttons, e.g. via div.html('');
// add the buttons' click handlers
});
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>