looking for a good pratice to hide and display some divs - javascript

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";
}
}

Related

Count and display most recent blog posts in javascript

What is the javascript in order to only display posts 3 & 4 in order???
Also I need it be dynamic so if I put a 5th post it will only display 4th and 5th posts... I was thinking about something like a date function or a simple incrementor but can't seem to figure it out. I'm new to javascript and have been trying different things but no avail... Thanks in advance...
<!DOCTYPE html>
<html>
<body>
<div id="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div id="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div id="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div id="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
<script>
// ???
</script>
</body>
</html>
You dont need script for that. You can do it with CSS.. I have changed your html little bit (made posts-div class in html).
.posts-div{
display:none;
}
.posts-div:nth-child(-n+2) {
display:block;
}
<!DOCTYPE html>
<html>
<body>
<div class="posts-div">
<h1 class="post-title">post5</h1>
<p class="post">post5</p>
</div>
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
<script>
// ???
</script>
</body>
</html>
You can test it on JSfiddle as well.. https://jsfiddle.net/nimittshah/b5eL3ykx/6/
$('.posts-div:gt(1)').hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
</body>
Try this:
<script>
document.addEventListener("DOMContentLoaded", function () {
var allPosts = document.querySelectorAll(".posts-div");
// This is the number of posts you want displayed
var numberOfPostsToShow = 2;
for (var i = 0; i < allPosts.length; i++) {
if(i > numberOfPostsToShow - 1) {
allPosts[i].style.display = "none";
}
}
});
</script>
This way you will choose how many posts you want to be shown with the numberOfPostsToShow variable.
Let me know if this worked. Regards.
The way I interpreted your question, you need a way to:
show only the first n elements;
add new elements to the top of the list of posts, dynamically;
when you add them, update the visible elements.
Assuming a slightly modified version of your code, which corrects the id/class issue and adds a container for all the posts (this time with a proper id):
<!DOCTYPE html>
<html>
<body>
<div id="posts-container">
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
</div>
<script>
// ???
</script>
</body>
</html>
this code will do the trick and manage both the addition and the updates to the visibility of the posts:
function showOnly(visible, query){
var elements = document.querySelectorAll(query);
for (var i = 0; i < elements.length; i++){
if (i < visible - 1){
elements[i].style.display = 'block';
} else {
elements[i].style.display = 'none';
}
}
}
function publishPost(element, visible){
showOnly(visible, '#posts-container .posts-div')
var elements = document.querySelectorAll('#posts-container .posts-div');
element.style.display = 'block';
if (elements.length > 0) {
document.querySelector('#posts-container').insertBefore(element, elements[0]);
} else {
document.querySelector('#posts-container').appendChild(element);
}
}
The showOnly function (to be called with the number of elements to be shown and the string that identifies the elements with querySelectorAll) will only make visible the first n elements identified by the string. You can use it independently of the rest of the code if needed.
The publishPost function, on the other hand, is strictly dependent on the modified html above (to use it elsewhere you will need to adjust the strings fed to querySelector and querySelectorAll). It takes the element to be published as the first argument, the number of elements that need to be visible as the second. Then it updates the list of posts prepending the new one to it, and it also updates which posts are visible.
This is a code sample that uses it:
var elDiv = document.createElement('div');
var elH1 = document.createElement('h1');
var elP = document.createElement('p');
elDiv.classList = 'posts-div';
elH1.classList = 'post-title';
elP.classList = 'post';
elH1.innerText = 'some title';
elP.innerText = 'some text for the post';
elDiv.appendChild(elH1).appendChild(elP);
publishPost(elDiv, 2);
showOnly
This function starts by getting a list of the elements whose visibility must be managed:
var elements = document.querySelectorAll(query);
then it loops through the list and examines each element:
for (var i = 0; i < elements.length; i++){
if it has to be visible, it sets the style.display property to 'block':
if (i < visible){
elements[i].style.display = 'block';
otherwise it sets it to 'hidden':
else {
elements[i].style.display = 'none';
publishPost
This function starts by showing only n-1 elements (because it will need to add a new, visible element to the top of the list):
showOnly(visible - 1, '#posts-container .posts-div')
then it retrieve the current posts:
var elements = document.querySelector('#posts-container .posts-div');
it makes the new element visible:
element.style.display = 'block';
finally, it adds the element to the top of the list (the different syntax depends on wether the list is empty):
if (elements.length > 0) {
document.querySelector('#posts-container').insertBefore(element, elements[0]);
} else {
document.querySelector('#posts-container').appendChild(element);
}

Check Div Elements by name fast

I have some Divs:
<div id="content">
<div class="c" id="1">
<div id="xyz">dont care</div>
<div id="texts1">
<div name="check"> ContentText </div>
</div>
</div>
<div class="c" id="2">
<div id="xuyz">dont care</div>
<div id="texts2">
<div name="check"> ContentText </div>
</div>
</div>
</div>
I want to iterate through all elements of the "c" class.
Then I want to check, if the Div elements named "check" of each "c" element contains special text.
If true, then manipulate the "c" element (which contains the special text)
I tried something like this:
var ele = document.getElementsByClassName("c");
for(var i=0;i<ele.length;i++)
{
var check = ele[i].getElementsByName("check");
if(check.innerHTML ....)
}
But thats not working :/
Log from Firefox:
TypeError: ele[i].getElementsByName is not a function
Where is my mistake?
A simple querySelectorAll() should do the trick:
var check = document.querySelectorAll('.c [name="check"]');
And as stated in a comment already, only document has getElementsByName method.
With jQuery this is very simple -
$('[name="check"]:contains("your special text")')
With jQuery (you have tagged it with it as well)
$(document).ready(function () {
$('div.c').find('div[name="check"]').each(function(){
// here check HTML and do needed manipulations
if($(this).html() == 'ContentText'){
$(this).closest('div.c').children().first().html('I CARE');
}
});
});
see jSFiddle -> http://jsfiddle.net/ApfJz/32/
Here is a modification of your code to make it work as intended
var ele = document.getElementsByClassName("c");
for (var i = 0; i < ele.length; i++)
{
if (ele[i].getAttribute('name') === "check") {
// do something with matching elements here
}
}

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.

Open sub link in the same page in html

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>

Attaching event handler to DOM elements

I am working on a tic tac toe game, which is almost complete. The only thing I am left wondering about is if it is possible to add an event handler for onclick from my .js file instead of directly calling it from an HTML attribute. Here is the bit of HTML that uses the onclick:
<div id="left">
<div id="board">
<div id="one" onclick="playerMove(this)">
</div>
<div id="two" onclick="playerMove(this)">
</div>
<div id="three" onclick="playerMove(this)">
</div>
<div id="four" onclick="playerMove(this)">
</div>
<div id="five" onclick="playerMove(this)">
</div>
<div id="six" onclick="playerMove(this)">
</div>
<div id="seven" onclick="playerMove(this)">
</div>
<div id="eight" onclick="playerMove(this)">
</div>
<div id="nine" onclick="playerMove(this)">
</div>
</div>
</div>
Any thoughts on the matter would be greatly appreciated.
If you use jQuery something like this should work:
$(document).ready(function() {
$('#board div').click(playerMove);
});
In plain javascript (no cross platform libraries), event handlers can be added via javascript code with addEventListener (modern browsers) or attachEvent (older versions of IE).
Here's a simple function that adds an event handler in a cross browser fashion:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
Example usage (called after the page DOM has loaded):
addEvent(document.getElementById("one"), 'click', playerMove);
Or, to install event handlers for all the board divs, you could do this:
var divs = document.getElementById("board").children;
for (var i = 0, len = divs.length; i < len; i++) {
// element nodes only
if (divs[i].nodeType === 1) {
addEvent(divs[i], 'click', playerMove);
}
}
You should really consider using jQuery for this. If you were using jQuery, this would have been as simple as:
$('#board > div').click(playerMove);
In case you want to stick with vanilla JS, you can do:
var items = document.getElementById('board').children;
for(x in items) {
items[x].onclick = function() {
playerMove(items[x]);
};
}
Use this:
document.getElementById('element_id').onclick = function(){ playerMove(this); };
For each Div, change 'element_id' with 'one', 'two', ...
Try:
document.getElementById('one').onclick();
For binding the event handler in js file:
var board = document.getElementById('board'),
divs = board.getElementsByTagName('div'),
i, len = divs.length;
for (i = 0; i < len; i++) {
divs[i].onclick = function() {
playerMove(this);
};
}
Your answer is in following 5 lines. Try it :) If someone copies/converts my code in new post or my post to j-query, That is welcome with no problem.
var yourDivID = document.getElementById('your_Div_ID');
yourDivID.addEventListener('click', function (){ playerMove(this); }, false);
function playerMove(divElement)
{
alert(divElement.id);
}
I have tried to put complete demo Here on jsfiddle.net, You can click any div out of nine to check its event if link does not work, then you can check the following code (working for me WIN7 and FireFox)
<html>
<head>
<title> Add Events Dynamically </title>
<script type="text/javascript">
function add_DivClick_Events() {
var nodes = document.getElementById('board').childNodes;
for (var i = 0; i < nodes.length; i++) {
if (i % 2 == 1) {
nodes[i].addEventListener('click', function () {
playerMove(this);
}, false);
}
}
}
function playerMove(divElement)
{
alert(divElement.id);
}
</script>
<style type="text/css">
#board div
{
width:20px;
height:20px;
border:2px solid;
}
</style>
</head>
<body onload='add_DivClick_Events()'>
<div id="left">
<div id="board">
<div id="one">
</div>
<div id="two">
</div>
<div id="three">
</div>
<div id="four">
</div>
<div id="five">
</div>
<div id="six">
</div>
<div id="seven">
</div>
<div id="eight">
</div>
<div id="nine">
</div>
</div>
</div>
</body>
</html>

Categories

Resources