I'm trying to make several divs and switch between them when different buttons are clicked.
Each div will hold something different, for instance the main div is visible on load, the rest are hidden and depending on which button you click you open that div while at the same time hiding the current div. Basically switching between divs smoothly without delay and such.
Below is what I got to, I have 2 divs, the main div is visible from get go, while the other is hidden in my css and when I click on button it displays, but my first div is still visible and I have to click button to make it hidden.
My question is how do I go about making an efficient if statement to make one div appear/visible by clicking a button while the current disappears and joins dosens other that are hidden until I click on their button?
I don't understand JavaScript very well and I want to understand how to do it so no JQuery please :)
And I'm asking about how to do this with divs because I don't know if there is any other way to do it, if there is then please share :)
Thanks
// Div One
var mainDiv = document.getElementById('button');
mainDiv.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
// Div Two
var upgradesDiv = document.getElementById('button2');
upgradesDiv.onclick = function() {
var div = document.getElementById('UpgradesDiv');
if (div.style.display !== 'block') {
div.style.display = 'block';
} else {
div.style.display = 'none';
}
};
I may not fully understand ultimately what you're trying to do. But given your example, you could wrap your div tags in a container and pass some indentifier to your function:
JS
function toggleDiv(target){
var div = document.getElementById('wrapper').getElementsByTagName("div");
if (target == 1) {
div[0].style.display = 'none';
div[1].style.display = 'block';
} else {
div[0].style.display = 'block';
div[1].style.display = 'none';
}
};
HTML
<div id="button" onclick="toggleDiv(0)">one</div>
<div id="button2" onclick="toggleDiv(1)">two</div>
<div id="wrapper">
<div id="newpost"></div>
<div id="UpgradesDiv"></div>
</div>
FIDDLE
Regular; plain-old-javascript way:
function onComplete() {
hide(getById('newPost'));
hide(getById('upgrades'));
clickAndToggle('button1', ['newPost']);
clickAndToggle('button2', ['upgrades']);
}
function clickAndToggle(buttonId, toggleTargetIds) {
var mainDiv = getById(buttonId);
mainDiv.onclick = function() {
toggleTargetIds.forEach(function(targetId) {
toggle(getById(targetId));
});
};
}
function getById(id) {
return document.getElementById(id);
}
function toggle(el) {
window[!isVisible(el) ? 'show' : 'hide'].call(undefined, el);
}
function hide(el) {
el.style.display = 'none';
}
function show(el) {
el.style.display = '';
}
function isVisible(el) {
return el.style.display !== 'none' && el.style.visibility !== 'hidden';
}
document.onreadystatechange = function() {
var state = document.readyState;
if (state == 'complete') {
onComplete();
}
};
<input type="button" id="button1" value="Button #1" />
<input type="button" id="button2" value="Button #2" />
<br />
<div id="newPost">New Post!</div>
<div id="upgrades">Upgrades!</div>
jQuery way
You can use $.hide() and $.show() to toggle visibility.
$(document).ready(function() {
$('#newPost').hide();
$('#upgrades').hide();
clickAndToggle('#button1', ['#newPost']);
clickAndToggle('#button2', ['#upgrades']);
function clickAndToggle(buttonId, toggleTargetIds) {
$(buttonId).click(function() {
$.each(toggleTargetIds, function(idx, targetId) {
//if(!($(targetId).is(":visible"))){$(targetId).show();}else{$(targetId).hide();}
$(targetId).toggle();
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button1" value="Button #1" />
<input type="button" id="button2" value="Button #2" />
<br />
<div id="newPost">New Post!</div>
<div id="upgrades">Upgrades!</div>
To me this seems the most straightforward way of doing this:
var first = 'newpost';
var currentDiv = document.getElementById(first);
function addDivToggle(buttonId, divId)
{
var button = document.getElementById(buttonId);
var newDiv = document.getElementById(divId);
button.addEventListener('click', function(){
currentDiv.style.display = 'none';
newDiv.style.display = '';
currentDiv = newDiv;
});
}
addDivToggle('button1', 'newpost');
addDivToggle('button2', 'UpgradesDiv');
Here i'm assuming that 'newpost' is already visible, and the other divs are hidden.
// The doClick() functions does what onClick() is supposed to do when clicked manually.
// Div One
var mainDiv = document.getElementById('button');
mainDiv.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
// add this function call
upgradesDiv.doClick();
};
// Div Two
var upgradesDiv = document.getElementById('button2');
upgradesDiv.onclick = function() {
var div = document.getElementById('UpgradesDiv');
if (div.style.display !== 'block') {
div.style.display = 'block';
} else {
div.style.display = 'none';
}
// add this function call
mainDiv.doClick();
};
Related
I'm trying to make it so that whenever you click on either the button OR div itself, the display toggles. But whenever I click on the input inside of the div, the div disappears.
How can this be made so that you can still click on the input and the div not disappear? I've tried setting a z-index to the input but this fails.
Appreciate any help, thank you.
function doThis() {
var el = document.querySelector('div');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
div {
background: lightgreen;
display: flex;
}
<button onclick='doThis()'>click me</button>
<div onclick='doThis()'>
text <input type="text">
</div>
If you want the input click not to trigger the div click, you can use event.stopPropagation() function. It prevents event bubbling (passing the event to higher level DOM-elements).
function doThis() {
var el = document.querySelector('div');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
div {
background: lightgreen;
display: flex;
}
<button onclick='doThis()'>click me</button>
<div onclick='doThis()'>
text <input onclick='event.stopPropagation()' type="text">
</div>
For a pure JavaScript solution (that doesn't need jQuery), see this answer from #Sabaz to How do I prevent a parent's onclick event from firing when a child anchor is clicked?:
document.getElementById("clickable").addEventListener("click", function( e ){
e = window.event || e;
if(this === e.target) {
// put your code here
}
});
Your code wont be executed if clicked on parent's childs
you can do this:
function doThis(evt) { // <-- new: add argument
evt.preventPropagation() // <-- new, works in all new browsers
var el = document.querySelector('div');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
And add to your html:
onclick='doThis(event)'
Why cant you implement event stopPropagation for all input objects, Try ..
// select elements with js selectors and bind it
document.querySelector('input').onclick = function(e){
e.stopPropagation()
};
and here is answer by Rex M
Just check the target element which is clicked
function doThis() {
if(event.target.nodeName != "INPUT"){
var el = document.querySelector('div');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am really new to JS and I'm having some issues.
So I have this JS file: that is basically the same function repeating with different <div id="">.
var button = document.getElementById("obj-trigger");
button.onclick = function () {
var div = document.getElementById("obj-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
var button = document.getElementById("lineas-trigger");
button.onclick = function() {
var div = document.getElementById("lineas-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
var button = document.getElementById("cultura-trigger");
button.onclick = function() {
var div = document.getElementById("cultura-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
var button = document.getElementById("igualdad-trigger");
button.onclick = function() {
var div = document.getElementById("igualdad-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
var button = document.getElementById("proyectos-trigger");
button.onclick = function() {
var div = document.getElementById("proyectos-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
var button = document.getElementById("estigmas-trigger");
button.onclick = function() {
var div = document.getElementById("estigmas-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
var button = document.getElementById("soy-trigger");
button.onclick = function() {
var div = document.getElementById("soy-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
var button = document.getElementById("tudef-trigger");
button.onclick = function() {
var div = document.getElementById("tudef-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
And it works perfectly when I am using ALL the functions, however if I remove a <div> from my HTML, let's say: <div id="estigmas-trigger">, my JS will work until it reaches:
var button = document.getElementById("estigmas-trigger");
button.onclick = function() {
var div = document.getElementById("estigmas-cont");
if (div.style.display !== "none") {
div.style.display = "none"
}
else {
div.style.display = "block";
}
};
All code below that will stop working, so no more collapsing. :(
Why is that? And... how can I fix it?
It's because button will be null if there are no element with id estigmas-trigger, and you should get error that you can't set value onclick on null, try adding a check to test if button is not null:
var button = document.getElementById("estigmas-trigger");
if (button) {
button.onclick = function() {
var div = document.getElementById("estigmas-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
}
Your error is caused because when you remove an element from the HTML and then your Javascript tries to refer to that element without proper protections, it causes a script error and the script aborts execution because of the error.
The second thing you need to do when learning Javascript (after learning how to write your first script) is to learn how to check for errors in the debug console in the browser. That will show you when you have execution errors that are aborting your script and they will usually show you what line the error occurs on.
In this case, you would attempt to get a DOM element with a line such as:
var button = document.getElementById("estigmas-trigger");
And, then you would attempt to use the button variable. But, if the estigmas-trigger element was not in the page, then button would be null and it would be an error to reference a property of null such as .onclick.
In addition, your code is horribly repetitive. You really should never copy nearly identical code multiple times into your code. Instead, create a reusable function and use that function multiple places or if your code is almost entirely identical except for one input parameter (which is the case for you), then you can just put the one input parameter into an array and loop through the array.
Here's a much more DRY implementation (this replaces all of your code):
var buttons = ["obj-trigger", "lineas-trigger", "cultura-trigger",
"igualdad-trigger", "proyectos-trigger", "estigmas-trigger",
"soy-trigger", "tudef-trigger"];
buttons.forEach(function(id) {
var button = document.getElementById(id);
if (button) {
button.addEventListener("click", function(e) {
var cont_id = this.id.replace("trigger", "cont");
var elem = document.getElementById(cont_id);
if (elem) {
var style = elem.style;
if (style.display !== "none") {
style.display = "none";
} else {
style.display = "block";
}
}
});
}
});
Summary of changes:
Put all the trigger ID values into an array of strings so you can just loop through each one that you want to apply identical code to.
Use .forEach() to loop through the array of strings.
Get the DOM element for each id and check to see if it is present before trying to use it (this will solve your original problem).
Use .addEventListener() to add the click event handler as this is much more scalable than .onclick because you can have multiple click handlers for the same element this way. It is a generally good habit to switch to use .addEventListener().
Rather than refer to the xxx-cont ids by name, just derive them from the xxx-trigger ids using a simple text replacement. This saves more duplication and typing in your code.
Get the xxx-cont object in the DOM and also check to see if it exists before attempting to use it (safe coding).
One way is:
var button = document.getElementById("estigmas-trigger");
//that way you prevent define a function in a null object
if(button){
button.onclick = function() {
var div = document.getElementById("estigmas-cont");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
};
}
Quick question. I have a button defined as:
<input type='button' id='button' value='Development View' >
A div tag that encloses the following information:
echo "<div id = 'content' style='display:none'>";
echo "<th>Development Status</th>";
echo "</div>";
Some JavaScript that runs whenever the button is clicked:
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('content');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
My ultimate goal is to toggle the visibility of a column in a dynamic HTML table but I can't even get this simple header tag toggling. I do not get an error message but the button does nothing it seems. I am echoing out the HTML because this is a PHP script.
Wrap your javascript in a window.onload event
window.onload = function () {
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('content');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
}
};
Ruby on Rails 3. I am trying to get a button to show or hide a div.
This is not returning any errors but nothing happens.
<input type=button value="Show Archived Postings" onclick="showHide('oldNews');">
<div id="oldNews">
<%= render 'archive_news' %>
</div>
<script language="javascript" type="text/javascript">
function showHide(elementId) {
if (document.getElementById) {
var element = document.getElementById(elementId);
if (element.style.visibility == 'visible') {
element.style.visibility = 'hidden';
} else if (element.style.visibility == 'hidden') {
element.style.visibility = 'visible';
}
}
}
</script>
It will always render my 'archive_news'. What am I doing wrong? Thank you
You can use this code for your requirement. You can use style property for hide and display element when you click on button.
//this would hide when body is loaded
var element = document.getElementById('oldNews');
if(element != null){
element.style.display = 'none';
}
//this would hide when you click on input button
function showHide(elementId) {
var element = document.getElementById(elementId);
if (element != null) {
if(element.style.display != 'none'){
element.style.display = 'none';
}else{
element.style.display = 'block';
}
}
}
I have an arrow on my site that I'd like if onclick, it hides one element, and shows another. Hitting it again, will hide the element that was shown and show the element that was hidden.
For example, I have
<div id="arrow">▾</div>
<div id="ad"></div>
<div id="description">Hidden</div>
<div id="nav">Also Hidden</div>
So at first, the ad is showing, and then one you've clicked the arrow, I'd like the ad to hide, and then unhide the description and nav.
With jQuery, use .toggle():
$("#arrow").click(function () {
$("#ad, #description, #nav").toggle();
});
DEMO.
With plain JavaScript, you need to toggle the display property of each element manually:
document.getElementById("arrow").onclick = function () {
var description = document.getElementById("description");
var nav = document.getElementById("nav");
var ad = document.getElementById("ad");
if (ad.style.display == 'none') {
ad.style.display = '';
nav.style.display = 'none';
description.style.display = 'none';
} else {
ad.style.display = 'none';
nav.style.display = '';
description.style.display = '';
}
};
DEMO.
Try this (Since you asked for plain javascript)
window.onload=function(){
var arrow=document.getElementById('arrow').getElementsByTagName('a')[0];
arrow.onclick=function(){
var ad=document.getElementById('ad');
var description=document.getElementById('description');
var nav=document.getElementById('nav');
if(ad.style.display=='none')
{
ad.style.display='block';
description.style.display='none';
nav.style.display='none';
}
else
{
ad.style.display='none';
description.style.display='block';
nav.style.display='block';
}
return false;
};
};
DEMO.
DEMO
<input id="x" value="x" />
<input id="y" value="y" style="visibility:hidden" />
<input type="button" onclick="toggleBoth()" value="arrow" />
.
function toggle(id){
var elem = document.getElementById(id);
if(elem.style.visibility == 'hidden')
elem.style.visibility = 'visible';
else
elem.style.visibility = 'hidden';
}
function toggleBoth()
{
toggle('x');
toggle('y');
}