Clicked drop down menu - javascript

When I click menu text that should toggle the menuContent the first time, it works as it shows the menuContent which is what is meant to be shown. However, after it shows it does not hide so the display = block does not go back to display = none.
I tried using a show value but it did not work so I used display = block instead in an if statement.
(By the way: menu = button that toggles text and menuContent = text that should be shown or hidden)
This is the JavaScript:
menu.addEventListener('click', menuClick, false);
menuContent.style.display = 'none'
function menuClick() {
menuContent.classList.toggle('show');
if (menuContent.style.display = 'none') {
menuContent.style.display = 'block'
} else {
menuContent.style.display = 'none'
}
}
So the first part of the if statement worked but not the else part.
How do I fix this?

menuContent.style.display = 'none'
should be
menuContent.style.display === 'none'
otherwise you're setting menuContent back to "display: none" again.
Remind '=' and '==='!

menuContent.style.display = 'none' is variable assignment, not a test for equality. You need to use === or == (loose check).
So, you always end up in the first situation because you always assign it to a value.

Related

OnClick event to Hide and Toggle Page Section

I created two(2) sections.I want to hide a section by default, with a button under it that says “Show More”.
Something like this--- (https://www.livermoretreeremoval.com/tree-service-ulmar) under the "Ulmar Tree Services Top Sights" section.
If the button is clicked, the hidden Section should appear, and the button Text should change to “Show Less”.
If the Button is clicked again, the visible Section should become hidden again, and the Button Text should say “Show More”.
So when hidden, the button says “Show More”, and when visible the button says “Show Less”.
Here’s my JavaScript below:
`
function toggleBlock() {
// get the block
var myBlock = document.getElementById(‘service-area-two’);
// get the current value of the block’s display property
var displaySetting = myBlock.style.display;
// also get the block button, so we can change what it says
var blockButton = document.getElementById(‘Show More’);
// now toggle the block and the button text, depending on current state
if (displaySetting == ‘block’) {
// block is visible. hide it
myBlock.style.display = ‘none’;
// change button text
blockButton.innerHTML = ‘Show Less’;
}
else {
// block is hidden. show it
myBlock.style.display = ‘block’;
// change button text
blockButton.innerHTML = ‘Show More’;
}
}
`
The Section ID: service-area-two
The Button Name is: ToggleButton
I know I’m doing a lot of things wrong.
How can I get this button to work?
So as for the button, the show more and show less is not working is what I understood. I think the mistake here is innerHTML. innerHTML means the actual HTML inside the block like for example:
button.innerHTML = '<img src="---'">'
Finally, change innerHTML to innerText.
Use the hidden attribute.
So:
<div hidden id="service-area-two">
// content
</div>
<button id="Show More" onclick="toggleBlock()">Show more</button>
And the JavaScript logic like this:
function toggleBlock() {
var myBlock = document.getElementById("service-area-two");
var blockButton = document.getElementById("Show More");
if (myBlock.hidden) {
blockButton.innerHTML = "Show Less";
myBlock.hidden = false;
} else {
blockButton.innerHTML = "Show More";
myBlock.hidden = true;
}
}

Toggle visibility for multiple divs with one function: navigation bar

My Assignment: Hi! I am doing an assignment in school where I am supposed write code in Javascript in order to toggle visibility for the submenus each belonging to their own topmenu in a navigation bar for a webpage. The visibility should be set to hidden by default and should be shown when a topmenu is clicked on.
I know how to toggle visibility for ONE submenu belonging to a topmenu, but fail to make my code work for multiple elements. My HTML-code:
<a class="left_top1" onclick = "toggle()">Opinion</a><br>
<div class="left_submenu_1" style="display: none;">
<a class="left_sub1">Leaders</a><br>
<a class="left_sub1">Debates</a><br>
</div>
<br>
<a class="left_top2" onclick = "toggle()">Economy</a><br>
<div class="left_submenu_2" style="display: none;">
<a class="left_sub2">News</a><br>
<a class="left_sub2">Your Economy</a><br>
</div>
My Problem: The topmenus I speak of are "Opinion" and "Economy". The visibility of the div with the class "left_submenu_1" should be toggled when you click the topmenu "left_top1". Thus should the visibilily of the div with the class "left_submenu_2" be toggled when you click the topmenu "left_top2". This is what I fail to do. My Javascript code is so far:
function toggle() {
var e = document.querySelectorAll("div.left_submenu_1, div.left_submenu_2");
for (var i=0; i < e.length; i++) { // I know this will enable/disable the visibility for ALL elements selected from the querySelectorAll, which should NOT happen
if(e[i].style.display == "none") {
e[i].style.display = "block";
} else if(e[i].style.display == "block") {
e[i].style.display = "none";
}
}
}
Anyone who knows how to solve this issue of mine? I know there are errors in the for-loop (as I wrote next to it), but this is the best I can manage for now.
Please note: We are NOT allowed to use jQuery or to give the topmenus id:s, as the idea is to use one general function to toggle the visibility. Furthermore, the code which enables the toggle-function should be done in Javascript.
I would approach it by passing the class name of the div to be shown (or hidden) into the function to begin with.
HTML
<a class="left_top1" onclick = "toggle('.left_submenu_1')">Opinion</a>
Then in the function you can grab the element and toggle it's display state.
JavaScript
function toggle(qs) {
var e = document.querySelector(qs);
e.style.display = e.style.display === 'block' ? 'none' : 'block';
}
The e.style.display === 'block' ? 'none' : 'block' part is saying if the elements display state is equal to block, return none, otherwise return block.
The return value is set as the new element display state due to the e.style.display = beforehand.
Tring to make it work modifying it as less as possible :
- use onClick="toggle(this)" in the anchors tags
- use a bit different toggle function like:
function toggle (el) {
var e = document.querySelectorAll('.' + el.className.replace('top', 'submenu_'))[0];
e.style.display = e.style.display.match(/none/) ? '' : 'none';
}
hope it helps, but I have to suggest You to make a small step forward and search for event delegation. Bye

Remove Class when current toggle is clicked

The title is a bit of a tongue twister. A brief description of the fiddle, is that it's a toggle style accordion where the toggle state changes color when one of the divs is toggled. I've got it working to where if another div is toggled it will close that previous div and open the new div while changing the toggle state.
The issue I am running into is if a user wants to close the current toggle without clicking a different div it will close the current toggle but not change the toggle state back to it's original state. I am currently using this and have tried multiple things including if the container 'is: visible' or hasClass then to remove the toggle class, but nothing seems to work. I've also tried a different slideToggle function, but of course that applied it to the toggled element I've found.
Fiddle: http://jsfiddle.net/NFTFw/1256/
What I am trying to do?
I want the current toggle class to change back to its original state if the user clicks the current toggled div or clicks another div. So essentially I want the user to have either option.
CODE:
$(document).ready(function () {
$('.column').each(function (index) {
$(this).delay(750 * index).fadeIn(1500);
});
$('.column').hide();
$('.body').hide();
$('.column').each(function () {
var $toggle = $(this);
$('.toggle', $toggle).click(function () {
$(".toggle").removeClass("toggle-d");
$(this).addClass('toggle-d');
$body = $('.body', $toggle);
$body.slideToggle();
$('.body').not($body).hide();
});
});
});
Check to see if the thing that you're clicking already has the class. If so, remove it, if not, add it. I suspect the problem you were having with hasClass() is that you were attempting to check the wrong this.
Oooh I did a bad thing and didn't remove the class when a new div was clicked. I've fixed that and updated the jsfiddle
jsfiddle
js:
$(document).ready(function () {
$('.column').each(function (index) {
$(this).delay(750 * index).fadeIn(1500);
});
$('.column').hide();
var width = $(window).width();
if (width <= 600) {
$('.body').hide();
$('.column').each(function () {
var $toggle = $(this);
$('.toggle', $toggle).click(function () {
if($(this).hasClass('toggle-d')){
$(this).removeClass("toggle-d");
}
else{
$('.toggle').removeClass('toggle-d');
$(this).addClass('toggle-d');
}
$body = $('.body', $toggle);
$body.slideToggle();
$('.body').not($body).hide();
});
});
}
});
What i would suggest is to pass the element itself in the function
in the index.html Do this
<a class = 'classname' onclick = toggle(this)>
Your Content Here
</a>
After that in the script.js
what i am saying is in javascript, i believe you can easily convert it to jquery
function toggle(value){
if(value.className == 'the predefined value'){
value.className = value.className + ' Your new class addition'
// remember there should be a space if you are adding an additional class to the present class, else directly change the classname
}
else{
value.className = 'the predefined value'
}}
this will toggle your classname whenever the element is clicked

Why JavaScript didint see that id visibility is set to hidden

Hi I whant that some element in my page appears only when a check box is selected, and disappears when it is not.
So I have this HTML:
<td><input type="checkbox" onchange="test('f1')"> Is selected?</td>
<div id="f1">some content</div>
And JavaScript:
function test(id) {
if (document.getElementById(id).style.visibility === "hidden") {
document.getElementById(id).style.visibility = "visible";
} else {
document.getElementById(id).style.visibility = "hidden";
}
}
And CSS:
#f1 {visibility: hidden;}
Right now it is working but not perfect, because the first select is always hidden.
As Juhana stated in the comments, the answer you're looking, which is explained perfectly in the link - is that: .style.* only looks at inline elements, quote:
"The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style."
If you tweak your function a little bit to check if .style.visibility hasn't been set yet (thus ''), it'll toggle it upon first click.
function changeVisiblity() {
if ( getContent.style.visibility == "hidden" || getContent.style.visibility == '' ) {
getContent.style.visibility = "visible";
} else {
getContent.style.visibility = "hidden";
}
}
Secondly, try to teach yourself to keep away from onclick within HTML elements, as this makes it much harder to maintain the future.
var getCheckbox = document.getElementById("testcheckbox"),
getContent = document.getElementById("f1");
getCheckbox.addEventListener( 'change', changeVisiblity, null );
Demo Fiddle: http://jsfiddle.net/4yfWD/

menu is not active after clicking the link..(after page loads)

finally i did this by following javascript..
function extractPageName(hrefString)
{
var arr = hrefString.split('/');
return (arr.length<2) ? hrefString : arr[arr.length-2].toLowerCase() + arr[arr.length-1].toLowerCase();
}
function setActiveMenu(arr, crtPage)
{
for (var i=0; i<arr.length; i++)
{
if(extractPageName(arr[i].href) == crtPage)
{
if (arr[i].parentNode.tagName != "DIV")
{
arr[i].className = "selected";
arr[i].parentNode.className = "selected";
}
}
}
}
function setPage()
{
hrefString = document.location.href ? document.location.href : document.location;
if (document.getElementById("but_a")!=null)
setActiveMenu(document.getElementById("but_a").getElementsByTagName("a"), extractPageName(hrefString));
}
if i click the ul without clicking the link.. its working.. when i click the link. it works until the page loads. after the page load, the ul back groud going default class not "selected" class..am new to tis.. am struggling so hard.. need help..??
I've added a jdFiddle with an example here:
http://jsfiddle.net/Suren/u4szQ/1/
$(document).ready(function() {
$("a.button").click(function () {
$(this).toggleClass("selected");
});
});
You've got too much javascript there.
After your posted fiddle. Here is a working fiddle.
Note you have a great deal of malformed HTML. You can't place divs in between list items. You can't have multiple objects on a page with the same ID (use a class instead).
After clicking on anchor the page is going to navigate to the url set on anchor's href attribute so whatever javascript operation you do is going to be lost after the page is loaded.
If you want to highlight the selected link the you can probably send the link id or some identifier along with the url and then check for it on page load and set the appropriate link selected.
By the way toggleClass adds or removes one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

Categories