Im completely new to Javascript, this is what i want:
Guy clicks on an element, so i trigger an onclick and i want to run a JS function, all clear so i need a JS function, what this function needs to do:
Check if the display of element #mobilemenu is block or none.
When it is block change it to none, when its none change it to block.
What i found so far was this:
function Change(){
document.getElementById("mobilemenu").style.display = "block"; }
But i am stuck on checking if it is currently block or none. I am kinda new to JS so maybe it is super easy (as i think) but i can't find a proper tutorial or some examples.
Thanks in advance!
You can use an if/else statement to check whether the element is displayed, and then show or hide it accordingly:
function Change() {
/* Put the mobilemenu into a variable */
var mobilemenu = document.getElementById("mobilemenu");
/* Check the display property of the element's style object */
if (mobilemenu.style.display !== "block") {
/* The element isn't display: block; so show it */
mobilemenu.style.display = "block";
} else {
/* The element is display: block; so hide it */
mobilemenu.style.display = "none";
}
}
Just add an if-else.
function Change(){
var displayVal = document.getElementById("mobilemenu").style.display;
if (displayVal == "block")
document.getElementById("mobilemenu").style.display = "none";
else if (displayVal == "none")
document.getElementById("mobilemenu").style.display = "block";
}
Here is a Fiddle: http://jsfiddle.net/vaa9goLe/
Also, you can use getComputedStyle in case your element doesn't have initial display value to ensure your function will always work.
var element = document.getElementById('btn');
element.onclick = function() {
var mydiv = document.getElementById('mydiv'),
isVisible = (mydiv.currentStyle || window.getComputedStyle(mydiv, '')).display == 'block';
if (isVisible){
mydiv.style.display = 'none';
} else {
mydiv.style.display = 'block';
}
};
jsfiddle:
http://jsfiddle.net/ykypcmt2/
This may help you
<div id="mobilemenu" style="display:block"></div>
<script type="text/javascript">
function Change(){
var contentId = document.getElementById("mobilemenu");
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
If the div had style value anything other than block or none , the following code should do nothing and preserve the original style value.
function Change(){
document.getElementById("mobilemenu").style.display = ( document.getElementById("mobilemenu").style.display === "block" ) ? "none" : ( document.getElementById("mobilemenu").style.display === "none" ) ? "block" : document.getElementById("mobilemenu").style.display ;
}
Related
When I click on the .current-pet-icon div, I need to click it twice before it shows my menu. but every subsequent click after is okay. Just when I refresh / load the page the first time I need to double click. Any help wpuld be greatly appreciated!
Javascript
const menuToggle = document.querySelector('.current-pet-icon')
const openedNav = document.querySelector('.nav-popout');
const shadowNav = document.querySelector('.shadow-nav');
menuToggle.addEventListener('click', () => {
if (openedNav.style.display === "none") {
openedNav.style.display = "block";
shadowNav.style.display = "block";
} else {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});
shadowNav.addEventListener('click', () => {
if (openedNav.style.display = "block") {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});
HTML
<div class="pet-icon-container">
<img class="current-pet-icon" src="https://www.burgesspetcare.com/wp-content/uploads/2021/08/Hamster.jpg" alt="current pet icon">
</div>
Assuming that there is a CSS style assigned to hide both .nav-popout and .shadow-nav elements initially then a modified version of the original js code appears to function as expected.
const menuToggle = document.querySelector('.current-pet-icon')
const openedNav = document.querySelector('.nav-popout');
const shadowNav = document.querySelector('.shadow-nav');
menuToggle.addEventListener('click', (e)=>{
openedNav.style.display = openedNav.style.display == 'block' ? 'none' : 'block';
shadowNav.style.display = shadowNav.style.display == 'block' ? 'none' : 'block';
});
shadowNav.addEventListener('click', (e)=>{
if( openedNav.style.display == "block" ) {
shadowNav.style.display = openedNav.style.display = "none";
}
});
.pet-icon-container img{
width:150px;
}
.nav-popout,
.shadow-nav{
display:none;
}
<div class="pet-icon-container">
<img class="current-pet-icon" src="https://www.burgesspetcare.com/wp-content/uploads/2021/08/Hamster.jpg" alt="current pet icon" />
</div>
<div class='nav-popout'>#NAV-POPOUT#</div>
<div class='shadow-nav'>#SHADOW-NAV#</div>
A quick console.log(openedNav.style.display) will help you find the issue. In the first call to the click handler, openNav.style.disply is actually empty (not 'none').
Why does this happen
If you access a DOM Element via getElementById, you'll not be able to read the computed style of that element, because it is defined inside the CSS file (I assume you are doing that).
How to fix it
use getComputedStyle. Or see the top answers to these questions if you wanna know more:
document.getElementById(...).style.display is blank
myDiv.style.display returns blank when set in master stylesheet
menuToggle.addEventListener("click", () => {
if (getComputedStyle(openedNav).display=== "none") {
openedNav.style.display = "block";
shadowNav.style.display = "block";
} else {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});
JavaScript:
let coll = document.getElementsByClassName('collection');
And I want to do something like that:
If the coll[0].style.display = 'block'; and you click on it, it will change to coll[0].style.display = 'none';.
(I want it to be possible to change on click display:block to display:none but ONLY when the display is set to block, I hope you know what i mean, please help)
let coll = document.getElementsByClassName('collection');
coll[0].onclick = () => {
if (coll[0].style.display = 'block') {
coll[0].style.display = 'none'
} else {
coll[0].style.display = 'block'
}
}
collection {
display: block;
}
<div class="collection">Click</div>
simply use
let coll = document.getElementsByClassName('collection');
coll[0].addEventListener('click', function() {
if (coll[0].style.display = "block") {
coll[0].style.display = "none";
}
});
div {
display: block;
}
<div class="collection">CLICK ME</div>
Inside your event listener, you can use this ternary operator:
coll[0].style.display === 'block'? coll[0].style.display = "hidden" : coll[0].style.display = "block"
You can learn more about ternary operators here.
By using this method I can show/hide an element by using 2 buttons:
<script type="text/javascript">
function showStuff(id) {
document.getElementById(id).style.display = 'block';
}
function hideStuff(id) {
document.getElementById(id).style.display = 'none';
}
</script>
<input type="button" onClick="hideStuff('themes')" value="Hide">
<input type="button" onClick="showStuff('themes')" value="Show">
<div id="themes" style="display:block">
<h3>Stuff</h3>
</div>
Is there a method to use a single button?? Maybe if & else?
You've already answered your question...the use of if/else:
function toggle(id) {
var element = document.getElementById(id);
if (element) {
var display = element.style.display;
if (display == "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
}
This won't be completely foolproof, in case you are hiding/showing inline or inline-block elements, or if you are using non-default values for display on elements...such as setting a div's display to "inline" (for whatever reason) and then trying to use this function
Yes if/else will work
function toggle(id){
var elem = document.getElementById(id);
if(elem.style.display == 'block'){
elem.style.display == 'none'
} else if(elem.style.display == 'none'){
elem.style.display == 'block'
}
}
I think you mean something like this:
function toggle(id){
var elem = document.getElementById(id);
if(elem.style.display == "block"){
elem.style.display="none";
} else {
elem.style.display="block";
}
}
Here is an alternate solution. Instead of using document.getElementById, you can also use document.querySelector which returns the first Element within the document that matches the specified selector, or group of selectors.
Solution Code:
function toggleShow() {
var elem = document.querySelector(id);
if(elem.style.display == 'inline-block'){
elem.style.display="none";
}
else {
elem.style.display = "inline-block";
}
}
I have used a javascript to show div by onclick but when i click outside div i want to hide the div.
after more searches, i have found an function, and it works perfectly
but there is an issue, the code requires double click for first time, to show the dive
my code:
<script>
// click on the div
function toggle( e, id ) {
var el = document.getElementById(id);
el.style.display = ( el.style.display == 'none' ) ? 'block' : 'none';
// save it for hiding
toggle.el = el;
// stop the event right here
if ( e.stopPropagation )
e.stopPropagation();
e.cancelBubble = true;
return false;
}
// click outside the div
document.onclick = function() {
if ( toggle.el ) {
toggle.el.style.display = 'none';
}
}
</script>
<style>#tools{display:none;}</style>
<div id="tools">Hidden div</div>
show/hide
This is my full code, you can test it on your computer.
The question is: The function requires two clicks, i want show the div on click ( one click ) Not ( Double Click )
Try this - http://jsfiddle.net/JjChY/1/
Change
el.style.display = ( el.style.display == 'none' ) ? 'block' : 'none';
to
el.style.display = (el.style.display == 'none' || el.style.display == '') ? 'block' : 'none';
Use this:
el.style.display = window.getComputedStyle(document.getElementById("tools")).getPropertyValue("display") == "none" ? 'block' : 'none';
It should work.
The problem is that el.style.display only reads from the element's inline styles, not its CSS.
So, on the first click el.style.display is '' (blank string), so it's set to 'none'. Then the second time, el.style.display is 'none', so it works.
You need to try to read from the element's CSS if its inline styles are blank. I'm going to use the getStyle method from quirksmode for this:
function getStyle(x, styleProp) {
if (x.currentStyle) {
var y = x.currentStyle[styleProp];
}
else if (window.getComputedStyle) {
var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
}
return y;
}
// click on the div
function toggle(e, id) {
var el = document.getElementById(id);
var display = el.style.display || getStyle(el, 'display');
el.style.display = (display == 'none') ? 'block' : 'none';
// save it for hiding
toggle.el = el;
// stop the event right here
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true;
return false;
}
// click outside the div
document.onclick = function() {
if (toggle.el) {
toggle.el.style.display = 'none';
}
}
DEMO: http://jsfiddle.net/JjChY/2/
Your code is a little convoluted. It can be written much simpler:
<script>
var toggle = function(id) {
var element = document.getElementById(id);
element.className = element.className === 'hidden' ? '' : 'hidden';
return false;
};
</script>
<style>
.hidden {
display: none;
}
</style>
<div id="tools" class="hidden">Hidden div</div>
show/hide
If you have jQuery, you could do something like this for the click outside.
First, set a class on the "tools" div when the mouse is inside it. Remove the class when the mouse is not inside it.
$('#tools').hover( function() {
$('#tools').addClass("inside");
},
function() {
$('#tools').removeClass("inside");
});
Then, track clicks on the HTML. Hide if the "inside" class is not on the "tools" div.
$("html").click( function() {
$("#tools").not(".inside").each( function() {
$("#tools").hide();
});
});
I'm using this javascript code to have a couple "show/hide" toggled divs on my site:
<script language="javascript">
function toggledean() {
var ele = document.getElementById("toggleTextdean");
var text = document.getElementById("displayTextdean");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Show more";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide";
}
}
</script>
What should I add to this code to have the div be displayed upon loading the page with a specific #hash added to the URL?
Thank you very much.
This is not the javascript answer that you want, but you could try playing around with the :target pseudo selector. For instance,
<!-- HTML -->
<div id="foo">show this with #foo.</div>
<div id="bar">#bar shows this.</div>
<style type="text/css">
div {display: none}
:target {display: block}
</style>
Example: http://jsfiddle.net/ZAHns/4/ (thanks to Jared for the idea of adding the anchors).
Depending on what you are trying to do, this could possibly work, but think your requirements through.
Note: Take this response with a HUGE grain of salt -- don't use it.
To answer the actual question, use the following to determine if the hash is present:
var in_hash = location.hash.slice(1) === what_you_are_looking_for;
if (in_hash) ? /* IN HASH */ : /* NOT IN HASH */;
Something like this should work:
<script>
var hash = window.location.hash.replace('#', '');
if (hash) {
document.getElementById(hash).style.display = 'block'
}
</script>
If you've only got the one element, like your script has, you could just call the function to toggle it if any hash exists in the url:
<script type="text/javascript">
function toggledean() {
...
}
if (window.location.hash == '#dean') toggledean();
</script>
Or you could make your toggle script a little more universal:
<script type="text/javascript">
var hash = window.location.hash.replace('#', '');
function toggle (elementPartial) {
var ele = document.getElementById('toggleText'+elementPartial);
var text = document.getElementById('displayText'+elementPartial);
if(ele.style.display == 'block') {
ele.style.display = 'none';
text.innerHTML = 'Show more';
} else {
ele.style.display = 'block';
text.innerHTML = 'Hide';
}
}
if (hash) {
toggle(hash);
}
</script>
Additionally, you could make this a little simpler and more flexible using a javascript framework, like jQuery.
Others have answered the URL hash part, I'll just comment on the script:
> <script language="javascript">
The language attribute is deprecated, type is required, so:
<script type="text/javascript">
> function toggledean() {
> var ele = document.getElementById("toggleTextdean");
> var text = document.getElementById("displayTextdean");
>
> if(ele.style.display == "block") {
The default display property is '' (empty string) unless you have set it to "block" previously.
> ele.style.display = "none";
> text.innerHTML = "Show more";
> } else {
> ele.style.display = 'block';
> text.innerHTML = 'Hide';
> }
Given the very high probability that the div will have a display value of '' when first loaded, you are much better off testing for style.display = 'none', so:
if (ele.style.display == 'none') {
ele.style.display = '';
text.innerHTML = 'Hide';
} else {
ele.style.display = 'none';
text.innerHTML = 'Show more';
}