The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> Hide/Show Toggle
Slushie
post Apr 1 2020, 08:39 PM
Post #1





Group: Members
Posts: 2
Joined: 1-April 20
Member No.: 27,262



Hopefully this will be an easy fix for someone.
I'm trying to implement the Hide/Show toggle at https://www.w3schools.com/howto/tryit.asp?f...oggle_hide_show

The script part of it is

<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>


My question is, the page always starts with the item being shown, not hidden. How do I make it when the page is first loaded the item is hidden, not shown?

Thanks for any help with this.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
pandy
post Apr 1 2020, 09:28 PM
Post #2


Computer says no.
********

Group: WDG Moderators
Posts: 18,975
Joined: 9-August 06
Member No.: 6



Basically you just need to set #myDIV to display: none since the script you already have checks if display is none and if it is it sets it to block. If display is something other than none it sets it to none. So it doesn't matter what it is to start with for the script to work.

But it's bad practice to hide a toggle object by default because users without JS can't make it visible. For that reason it's better to let JS hide it when the page loads. That way it will always be visible if JS isn't available. The whole script block would look something like this.

CODE
function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}


// New stuff below

function init()
{
   document.getElementById('myDIV').style.display = 'none';
}

window.onload = init;



The function I called init() will hide #myDIV. The last line (window.onload...) will run that function when the page loads.

I would place the whole script block in HEAD rather than where it is in the example at w3schools though. If nothing else, it's neater.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Slushie
post Apr 2 2020, 09:01 PM
Post #3





Group: Members
Posts: 2
Joined: 1-April 20
Member No.: 27,262



Thank you pandy! smile.gif I appreciate it.

That worked perfectly.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
pandy
post Apr 2 2020, 09:05 PM
Post #4


Computer says no.
********

Group: WDG Moderators
Posts: 18,975
Joined: 9-August 06
Member No.: 6



Good. smile.gif
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 9th August 2020 - 04:13 PM