Onclick function that changes the css of a element - javascript

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();
});
});

Related

Why does my JS 'click event' only run once?

I created a click event that opens a previously 'hidden' div and closes it again once you click the same button.
However, it only runs once (one open and one close) - I'm at a loss to explain why it doesn't work if I click it again.
let readMore = document.getElementById('clickAbout');
let moreInfo = document.getElementById('about');
let changeSepa = document.getElementById('sepChange');
readMore.addEventListener('click', function(){
changeSepa.style.height = '2rem';
if (moreInfo.className == "") {
moreInfo.className = "open";
moreInfo.style.display = 'block';
} else {
moreInfo.style.display = 'none';
}
});
this happens because you're checking if className == "", but you are modifying the className to be "open". On the second click it checks the className which is now "open" and goes to the else block. On the third click you expect for it to go into the first block but the className is still "open".
For an easy fix just change the className in the else block
else {
moreInfo.className = "";
moreInfo.style.display = 'none';
}
Also i suggest you make use of the classList property on elements
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
using the class list it could look like this:
readMore.addEventListener("click", function () {
changeSepa.style.height = "2rem";
if (moreInfo.className == "") {
moreInfo.classList.add("open");
moreInfo.style.display = "block";
} else {
moreInfo.classList.remove("open");
moreInfo.style.display = "none";
}
});
Or even
readMore.addEventListener("click", function () {
changeSepa.style.height = "2rem";
moreInfo.classList.toggle("open");
if (moreInfo.className == "") {
moreInfo.style.display = "block";
} else {
moreInfo.style.display = "none";
}
});

create a button that shows or hides a div depending on whether it is currently showing

I'm fairly new in with JS and was wondering, if
there is a more cleaner way of writing this code?
I'm trying to create a button that shows or hides a div depending on whether it is currently showing.
Many Thanks in Advance
Anne
var button = document.getElementById('button');
var hideText = document.getElementById('output').className = 'hide';
button.addEventListener('click', ()=>{
if(hideText){
document.getElementById('output').className = 'unhide';
hideText = false;
}else{
document.getElementById('output').className = 'hide';
hideText = true;
}
})
CSS
.hide{display: none;}
.unhide{display: block;}
Just use a single class (e.g. unhide) and make it invisible by default. Then do
button.addEventListener('click', () => {
document.getElementById('output').classList.toggle('unhide');
}
You can just toggle the classes
button.addEventListener('click', () => {
document.getElementById('output').classList.toggle('hide');
}
You can remove the extra variable hideText and also the extra css if you implement like this
var x = document.getElementById("output");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
In jquery the are other simpler possible way like toggle, hide, show.

JavaScript doesn't work after I remove one <div> [closed]

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

When element got visible in Javascript it toggle back to hidden

Please help as when ever i clcik and call Javascript function to unhide an element it turn back hidden again. it takes a second or less.
HTML
<asp:Button ID="btnFromCalOpen" Width = "35" runat="server" Text=">" style="display:none; visibility:hidden;" OnClientClick ="ShowCal()" />
Javascript
function ShowCal() {
var elem = document.getElementById('MainContent_CalendarFrom');
if (elem.visibility = "hidden" ) {
alert("Show");
elem.style.visibility = "visible";
elem.style.display = "inline";
}
else {
alert("Hide");
elem.style.visibility = "hidden";
elem.style.display = "none";
}
}
it like when ever i click on the button it refresh its style properties of all elements
Please help
You have an error/bug on your code here
if (elem.visibility = "hidden" ) {
you not check for the if, but you set it hidden !
To avoid this kind of errors try this way / trick
if ("hidden" == elem.visibility ) {
Two major problems in your code.
elem.visibility is not an attribute of your object. If you want to look at the style setting, it would be elem.style.visibility.
A comparison is done with == or ===, not with =. You were doing an assignment operation with =.
Try this code:
function ShowCal() {
var elem = document.getElementById('MainContent_CalendarFrom');
if (elem.style.visibility == "hidden" ) {
alert("Show");
elem.style.visibility = "visible";
elem.style.display = "inline";
}
else {
alert("Hide");
elem.style.visibility = "hidden";
elem.style.display = "none";
}
}
FYI, there's no need to set both style.visibility and style.display. If you're going to set style.display to "none", then the visibility setting isn't needed.
A simpler version of your code would be this (which you can see working here in this jsFiddle):
function ShowCal() {
var elem = document.getElementById('MainContent_CalendarFrom');
if (elem.style.display == "none" ) {
elem.style.display = "inline";
} else {
elem.style.display = "none";
}
}
And, remove the visibility: hidden from the HTML for this tag. The display: none is all you need.
For reference (in case this is a possibility), this is one of those places that libraries like jQuery or YUI are handy. In jQuery this would just be:
function ShowCal() {
$("#MainContent_CalendarFrom").toggle();
}

Javascript toggle issue

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.

Categories

Resources