This is my script :
window.onload = function (){
var title = document.getElementsByTagName('h1')[0].id = "heading1";
document.getElementById(title).onclick = function (e){
var para = this.nextSibling.style.display = 'block';
var newVal = (para == "block") ? "none" : "block";
alert(newVal);
}
}
The result I need is for the alert value to toggle from block to none and back. But I am always getting "none". What is the problem with my code?
window.onload = function () {
var firstH1 = document.getElementsByTagName('h1')[0];
firstH1.id = "heading1";
firstH1.onclick = function() {
var currentValue = this.nextSibling.style.display;
this.nextSibling.style.display = (currentValue == "none") ? "block" : "none";
}
}
Note a few things: I simplified your element fetching because it doesn't make sense to fetch an element, assign it an id, then use that id to find that same element again.
I also switched block/none ordering, because if no style is displayed then it would be blank -- and your first click would assign block to it - and it would not disappear. This way it does.
Well, para will always be "block", and therefore newVal will always be "none". So that behavior is expected. What are you trying to do? you are not toggling the property with your curent code.
Related
I'm working on a website where I want to show and hide images by clicking on a button/word. I used bit of code and it's working:
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
Similar to the one used in a previous stack overflow question on this topic:
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
However, I want the image to be hidden when you enter or refresh the site instead of shown. So instead of it starting by showing the image and hiding it when you click on the word, I want it to be hidden and shown when you click the word. How do I change the script to make that happen?
I tried to switching the "none" and "block" but it didn't work haha...
Thanks
You can hide the image when the script runs, which is when the page is loaded or refreshed.
So just adding one line is enough.
const button = document.getElementById("button") // Assumes element with id='button'
const imageElement = document.getElementById("newpost")
// Hide the image at the start
imageElement.style.display = "none"
// Toggle it on click
button.addEventListener('click', () => {
imageElement.style.display =
imageElement.style.display === "none" ? "block" : "none"
})
I also modified your code to make it a bit easier to read by using a ternary operator.
And in case you are using the .onClick method from the example: Prefer using addEventListener over .onX methods. More about that on MDN and on this answer.
I have an addEventListener for a dropdown menu and when I click it for the first time the menu appears, and if I click again it disappears correctly. However, after that if I try again nothing happens. If I get rid of the if statements and use a simple alert inside the function it works every time, but this if statement seems to be troublesome.
document.getElementById("menu").addEventListener("click",navigation);
function navigation() {
var navMenu = document.getElementById("navigation");
var list = document.getElementById("list");
if (navMenu.style.height == 0) {
navMenu.style.height = "190px";
list.style.display = "flex";
}
else {
navMenu.style.height = "0";
list.style.display = "none";
}
}
The element height is reported in pixels so updating the code like this should work.
if (navMenu.style.height === '0px') {
Here is a codepen http://codepen.io/anon/pen/ZOXAzd
In the condition, change
if (navMenu.style.height == 0)
to
if (navMenu.style.height == '0px')
and it should work.
I am not sure about this but have you tried to do = 0 instead of = '0'?
I hope this helped, good luck.
I now have this onclick function:
<p onclick="open3()" >Uw tuin blijft mooi door vakkundig en regelmatig onderhoud.</p>
function open3 ()
{
document.getElementById("c").style.display = "block";
}
What I want is that when I clicked on open three that it somehow changes it's value so I can click on it again to set style.display to none.
I tried this with a Boolean that set's it to true or false and then changes that but that didn't work
You can add an if statement that checks the current value of the applied style and changes it appropriately.
Using this approach you don't need to declare (and keep) any additional variable in your code, while still being able to achieve the desired effect.
An example is shown below.
function open3 () {
var c = document.getElementById('c');
if (c.style.display === 'block') {
c.style.display = 'none';
} else {
c.style.display = 'block';
}
}
Try using a check in the function:
function open3 () {
var c = document.getElementById("c");
if (c.style.display === 'block') {
c.style.display = 'none';
} else {
c.style.display = 'block';
}
}
Using pure Javascript:
function open3 ()
{
if (document.getElementById("c").style.display == "block")
document.getElementById("c").style.display = "none";
else
document.getElementById("c").style.display = "block";
}
Or you can use jQuery instead:
function opne3()
{
$("#c").toggle();
}
Hope it helps.
My approach is slightly different and creates a toggler function that returns a function to toggle whatever elements you pass into it with an initial state. You can keep reusing this function whenever you need to toggle an element so you don't repeat code.
var toggler = function(el, init) {
var flag = init;
return function(e) {
flag = !flag;
el.style.display = flag ? 'block' : 'none';
};
}
Create a new function passing in the element to be toggled and its initial state.
var toggleC = toggler(document.querySelector('#c'), false);
Remove the inline JS (best practice) and use addEventListener to target the element instead.
document.querySelector('#clicker').addEventListener('click', toggleC);
DEMO
A short version of the if/else answers on this page:
function open3 () {
var c = document.getElementById('c');
c.style.display = (c.style.display == 'block' ? 'none': 'block');
}
Try this
HTML:
<p id="togglethingy">Uw tuin blijft mooi door vakkundig en regelmatig onderhoud.
CSS:
#togglethingy{
display:block;
}
jQuery:
$(function(){
var $tog_ele = $("#togglethingy")
$tog_ele.click(function() {
$tog_ele.toggle();
});
});
My onclick function won't fire unless it is clicked twice. I am very new to javascript but so far i trie moving around the var obj line, and changing the =="none" to "none"?"empty"; which are both things I didn't understand but saw other people did to fix this problem. Neither worked.
+
function showDiv(id){
var obj = document.getElementById(id);
if( obj.style.display == "none") {
obj.style.display='block'
}
else{
obj.style.display='none'
}
}
<div id="show1">
Roughly 2-3 months.
</div>
Your problem is, that you use the style property of the element directly. Assuming, that you did not set obj.style.display = "none"; in your code explicitly, the value remains undefined until the first click. After the first click it is set and everything works like you want it to.
To solve it use getComputedStyle() to access the element's style. This includes all styles set via CSS:
function showDiv(id){
var obj = document.getElementById(id),
compStyle = window.getComputedStyle( obj );
if( compStyle.display == "none") {
obj.style.display='block'
} else {
obj.style.display='none'
}
}
You should use strict equal operators to prevent from undefined style rule.
I would rather use addEventListener instead of onclick to keep my code cleaner, here is a jsfiddle with my version (some extras as dataset and triple conditional are there, but they are not necessarily needed in your example)
var showDiv = function (ev) {
var id = ev.currentTarget.dataset.id;
var obj = document.getElementById('show' + id);
obj.style.display = (obj.style.display === "none") ? 'block' : 'none';
};
http://jsfiddle.net/mindcookin/06nvkay7/4/
I've been playing with javascript to create a drop down list that shows a div depending on which option is selected.
All the code can be seen here:
http://jsfiddle.net/nmdTy/
var select = document.getElementById('test'),
onChange = function(event) {
var shown = this.options[this.selectedIndex].value == 1;
document.getElementById('hidden_div').style.display = shown ? 'block' : 'none';
};
I want to know how do I streamline this code and remove repetition - maybe some kind of loop?
Another code :
var select = document.getElementById('test'),
nbItems = 2,
onChange = function (event) {
var val = this.options[this.selectedIndex].value;
for (var i = 1; i <= nbItems; i++) {
document.getElementById('hidden_div' + i).style.display = val == i ? 'block' : 'none';
}
};
http://jsfiddle.net/nmdTy/11/
You don't need two event handlers, you can use variables (shown below) to determine which div needs to be displayed or hidden.
var select = document.getElementById('test'), onChange = function(event) {
var div1 = 'hidden_div';
var div2 = 'hidden_div2';
var index1 = this.options[this.selectedIndex].value == 1;
var index2 = this.options[this.selectedIndex].value == 2;
if(index1 || index2){
document.getElementById(div1).style.display = index1 ? 'block' : 'none';
document.getElementById(div2).style.display = index2 ? 'block' : 'none';
}
else{
document.getElementById(div1).style.display = 'none';
document.getElementById(div2).style.display = 'none';
}
};
// attach event handler
if (window.addEventListener) {
select.addEventListener('change', onChange, false);
} else {
// of course, IE < 9 needs special treatment
select.attachEvent('onchange', function() {
onChange.apply(select, arguments);
});
}
Working Fiddle
I'm not really sure what do you mean by "repetition" but my guess is, that you don't want to type every each of the divs to be hidden/shown.
There could be multiple approaches to such task. The most universal is to have the div id's in a separate array. Then you can hide all but the selected div.
var divs = ["hidden_div1", "special_hidden", "one_more_hidden"];
var select = document.getElementById('test');
var onchange = function(event) { //Use var!
var shown = this.options[this.selectedIndex].value;
for(var i=0; i<window.divs.length; i++) { //It would be more effective to save last shown div in a variable, but I've chosen this aproach with loop
var div = document.getElementById(window.divs[i]);
if(div!=null) {
if(i==shown)
div.style.display="block";
else
div.style.display="none";
}
}
};
select.addEventListener("change", onchange); //Could type the function right here, without using "onchange" variable
In my code, <option> value represents index in the array. Here is jsFiddle.
Delegating a change event in IE<9 is a pain. It is possible, check this question to see how it's done, but it's not what you call elegant.
But your code doesn't delegate the event, so just attaching the handler directly at the onload event should do the trick (and it's X-browser compatible):
document.getElementById('test').onchange = function(e)
{
e = e || window.event;//the only IE headache
var shown = this.options[this.selectedIndex].value == 1;
document.getElementById('hidden_div').style.display = shown ? 'block' : 'none';
//^^ could keep a reference to this in a closure
};
The full code (with onload and closure reference to hidden div and preventing memory leaks in ie) should look like this:
var winLoad = function(e)
{
var hiddenDiv = document.getElementById('hidden_div');
document.getElementById('test').onchange = function(e)
{
var shown = !!(this.option[this.selectedIndex].value == 1);//to be safe, coerce to bool
hiddenDiv.style.display = shown ? 'block' : 'none';
};
if (window.addEventListener)
{
return window.removeEventListener('load',winLoad,false);
}
return window.detachEvent('onload',winLoad);
};
if (window.addEventListener)
{
window.addEventListener('load',winLoad,false);
}
else
{
window.attachEvent('onload',winLoad);
}
that should work fine on all major browsers, even IE7 (probably IE6, too)