I want to change the style (second line below) to remove the display: none; part when the user clicks on the "Show All Tags" link. If the user clicks the "Show All Tags" link again, I need the display: none; text added back in to the "style..." statement.
Show All Tags
<ul class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">
I've searched here and Google for an example I can apply to my situation. I've found plenty of examples using 2 DIV blocks to show/hide. I really need to do it this way, by modifying the html style element. Does anyone have an example (or provide a link to an example) that does this type of toggle wtih the display: none text.
Give your ul an id,
<ul id='yourUlId' class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">
then do
var yourUl = document.getElementById("yourUlId");
yourUl.style.display = yourUl.style.display === 'none' ? '' : 'none';
IF you're using jQuery, this becomes:
var $yourUl = $("#yourUlId");
$yourUl.css("display", $yourUl.css("display") === 'none' ? '' : 'none');
Finally, you specifically said that you wanted to manipulate this css property, and not simply show or hide the underlying element. Nonetheless I'll mention that with jQuery
$("#yourUlId").toggle();
will alternate between showing or hiding this element.
Give the UL an ID and use the getElementById function:
<html>
<body>
<script>
function toggledisplay(elementID)
{
(function(style) {
style.display = style.display === 'none' ? '' : 'none';
})(document.getElementById(elementID).style);
}
</script>
Show All Tags
<ul class="subforums" id="changethis" style="overflow-x: visible; overflow-y: visible; ">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
Others have answered your question perfectly, but I just thought I would throw out another way. It's always a good idea to separate HTML markup, CSS styling, and javascript code when possible. The cleanest way to hide something, with that in mind, is using a class. It allows the definition of "hide" to be defined in the CSS where it belongs. Using this method, you could later decide you want the ul to hide by scrolling up or fading away using CSS transition, all without changing your HTML or code. This is longer, but I feel it's a better overall solution.
Demo: http://jsfiddle.net/ThinkingStiff/RkQCF/
HTML:
<a id="showTags" href="#" title="Show Tags">Show All Tags</a>
<ul id="subforms" class="subforums hide"><li>one</li><li>two</li><li>three</li></ul>
CSS:
#subforms {
overflow-x: visible;
overflow-y: visible;
}
.hide {
display: none;
}
Script:
document.getElementById( 'showTags' ).addEventListener( 'click', function () {
document.getElementById( 'subforms' ).toggleClass( 'hide' );
}, false );
Element.prototype.toggleClass = function ( className ) {
if( this.className.split( ' ' ).indexOf( className ) == -1 ) {
this.className = ( this.className + ' ' + className ).trim();
} else {
this.className = this.className.replace( new RegExp( '(\\s|^)' + className + '(\\s|$)' ), ' ' ).trim();
};
};
LEVEL - I
document.querySelector('.my-btn').addEventListener('click', myFunction);
function myFunction() {
document.querySelector('.subforums').classList.toggle("off");
}
.off {
display: none;
}
Show All Tags
<div class="subforums off">My text...</div>
LEVEL - II
Toggle hide element Id end className...
function toggleElem(newElem) {
var elem = document.getElementById('' + newElem + '');
var eIdent = (elem != null) ? ('#' + newElem) : ('.' + newElem);
elem = document.querySelector('' + eIdent + '');
elem.style.display = (elem.style.display != 'none') ? 'none' : 'block';
}
You can test directly from this link: https://codepen.io/pedro404/pen/VwmPBee
You can do this through straight javascript and DOM, but I really recommend learning JQuery. Here is a function you can use to actually toggle that object.
http://api.jquery.com/toggle/
EDIT: Adding the actual code:
Solution:
HTML snippet:
Show All Tags
<ul id="tags" class="subforums" style="display:none;overflow-x: visible; overflow-y: visible; ">
<li>Tag 1</li>
<li>Tag 2</li>
<li>Tag 3</li>
<li>Tag 4</li>
<li>Tag 5</li>
</ul>
Javascript code using JQuery from Google's Content Distribution Network: https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
$(function() {
$('#showAll').click(function(){ //Adds click event listener
$('#tags').toggle('slow'); // Toggles visibility. Use the 'slow' parameter to add a nice effect.
});
});
You can test directly from this link: http://jsfiddle.net/vssJr/5/
Additional Comments on JQuery:
Someone has suggested that using JQuery for something like this is wrong because it is a 50k Library. I have a strong opinion against that.
JQuery is widely used because of the huge advantages it offers (like many other javascript frameworks). Additionally, JQuery is hosted by Content Distribution Networks (CDNs) like Google's CDN that will guarantee that the library is cached in the client's browser. It will have minimal impact on the client.
Additionally, with JQuery you can use powerful selectors, adding event listener, and use functions that are for the most part guaranteed to be cross-browser.
If you are a beginner and want to learn Javascript, please don't discount frameworks like JQuery. It will make your life so much easier.
Related
so i'm a bit confused as why the code im working off isn't working as expected, so any help would be good.
so let me explain im working on an expanding/ collapsing menu, when the a tag is clicked a class is added and css is added to make this happen, and also the class is removed from the other links.
CSS code:
a {
max-height: 0;
overflow: hidden;
transition: 0.5s ease-in-out
}
a.clicked {
max-height: 600px;
}
html code:
<ul>
<li><a onclick='mobileMenu(event)'>link 1</a><li>
<li><a onclick='mobileMenu(event)'>link 2</a><li>
<li><a onclick='mobileMenu(event)'>link 3</a><li>
<li><a onclick='mobileMenu(event)'>link 4</a><li>
</ul>
for this post i kept the html pretty simple but if it needs to be more detailed let me know.
Each link has a onclick attached.
Javascript code:
function mobileMenu(event) {
event.currentTarget.classList.toggle("clicked");
[].forEach.call(document.querySelectorAll('ul li a'), function(a){
a.classList.remove('clicked');
});
}
so this code mostly works where you click a link is adds 'clicked' class and also removes the 'clicked' class from any other links except the current link, which is good because im using this as a collapse-able menu so you click another link it opens it while also closing any other link currently open.
My problem is is the js code above to add the clicked class i'm using a '.toggle' but this only adds the 'clicked' class but does not toggle it. I want to be able to toggle the 'clicked' class and also remove it from others links. so im not sure if its a simple oversight on my part but im not sure where im going wrong and why the '.toggle' isn't actually toggling the class.
Thanks.
You can try a if statement. It will always remove the checked from all links, and if the event.target is not checked, it will add the class checked.
function mobileMenu(event) {
const checked = event.currentTarget.classList.contains('clicked')
[].forEach.call(document.querySelectorAll('ul li a'), function(a){
a.classList.remove('clicked');
});
if (checked) return;
event.currentTarget.classList.toggle("clicked");
}
As per comment the right way to add event listeners is using .addEventListener().
In the event listener you can search for an anchor with a class clicked and if any remove the class. After you can add the class to the current element:
document.querySelectorAll('ul li a').forEach(function(ele, idx) {
ele.addEventListener('click', function(e) {
var clickedEle = document.querySelector('ul li a.clicked');
if (clickedEle != null)
clickedEle.classList.remove('clicked');
this.classList.add('clicked');
})
});
a {
max-height: 0;
overflow: hidden;
transition: 0.5s ease-in-out
}
a.clicked {
max-height: 600px;
color: blue;
}
<ul>
<li><a>link 1</a><li>
<li><a>link 2</a><li>
<li><a>link 3</a><li>
<li><a>link 4</a><li>
</ul>
I have a div with an i tag:
<div class="accordion-heading datalist" data-toggle="collapse" data-parent="#accordion2" href="##i.Id">div
<i class="fa fa-chevron-down table-middle" aria-hidden="true">i tag</i>
</div>
On first click of the div the i tag should disappear, on next click of the div the i tag should appear again. How can I do that?
You can use toggle() to achieve that:
$('.accordion-heading').click(function() {
$(this).find('i').toggle();
});
Note that depending on your styling rules, it may be hard and/or impossible to click the div element with the i hidden as it will have no height. To fix that you can set a min-height rule on the div, or put a non-breaking space ( ) in it.
I want to switch between display: none and display: tablecell
In this case you have to manage the display value yourself, like this:
$('.accordion-heading').click(function() {
$(this).find('i').css('display', function(i, d) {
return d == 'none' ? 'tablecell' : 'none';
})
});
use jquery toggle().
check this
jsfiddle
Without jQuery:
var accordion = document.querySelector('.accordion-heading');
accordion.addEventListener('click', toggleTag);
function toggleTag() {
var tagToToggle = accordion.querySelector('i');
if (!tagToToggle.classList.contains('active')) {
tagToToggle.classList.add('active');
} else {
tagToToggle.classList.remove('active');
}
}
CSS:
i {
display: none;
}
i.active {
display:block;
}
You can also use toggleClass() method but u create a css class for jquery function. its most customizeable
.display-none{display:none;} or
.display-none{opacity:0;transition:1s solid ease;}
$('.accordion-heading').on('click',function() {
$(this).find('i').toggleClass('display-none');
});
Click-Here to view example -jsbin
HTML code:
<div class="content">
<textarea> hello.png </textarea>
</div>
<div class="content-btn">
Click me
</div>
Javascript code:
$(".button").click(function() {
if ($(this).parent().previousSibling('.content').css('display') == 'none'){
$('.content').hide();
$(this).parent().previousSibling('.content').show();
}else {
$('.content').hide();
}
});
How would I go about only showing the textarea when 'Cick me' is clicked or hovered preferably in css but if not javascript. Thanks guys
https://jsfiddle.net/uway5hhg/8/
As exercise you could do this effect in pure css (using :target pseudoclass and a long delay in a simple transition) if you add a close button just below the textarea
http://codepen.io/anon/pen/JYoMRK
<div class="content" id="text">
<textarea> hello.png </textarea><br />
Close
</div>
<div class="content-btn">
Open
</div>
CSS
#text {
overflow: hidden;
height: 0;
opacity: 0;
transition: opacity 0s 999999s;
}
#text:target {
opacity: 1;
height: auto;
transition-delay: 0s;
}
#text:target ~ div a.button { display: none; }
Anyway if you look for a straight jQuery approach, a simple toggle() is enough (you might have to hide the .content element via css depending on the initial condition of your textarea)
https://jsfiddle.net/uway5hhg/39/
$(".button").click(function() {
var content = $(this).parent().prev('.content');
content.toggle();
});
As far as I know there is no way to catch previous sibling in CSS.
But it works with jQuery, here is your slightly changed code:
$(".button").on('click', function() {
var ele = $(this),
par = ele.parent(),
sbl = par.prev();
if (sbl.css('display') == 'none'){
$('.content').hide();
sbl.show();
}else {
$('.content').hide();
}
});
Working example is here: https://jsfiddle.net/y0ab3n0L/
That should do it's job
JS:
$(".button").click(function() {
var contentBtn = $(this).parent(".content-btn");
var content = $(contentBtn).prev(".content");
var textarea = $(content).find("textarea");
$(textarea).toggle();
});
or event shorter:
$(".button").click(function() {
$(this).parent(".content-btn").prev(".content").find("textarea").toggle();
});
https://jsfiddle.net/uway5hhg/21/
Hope this helps :)
Solution provided by Fabrizio is a good one if you want no javascript.
However you can also modify the DOM to have a similar effect.
<div class="content-wrapper">
<div class="content" id="text">
<textarea>hello.png</textarea>
</div>
Click me
</div>
CSS
.content {
display:none;
}
.content-wrapper:hover .content {
display:block;
}
.content-wrapper:hover .button {
display:none;
}
https://jsfiddle.net/2Lsszgqz/
There is no such CSS pseudo element - a.button:click, so only JS solution will work (without changing your HTML structure). You can also get to close of it using :focus CSS pseudo class. But you will lack to go up one level in CSS and then show the textarea. So, only solution left is using JS.
In your sample JS code you have used .previousSibling('.content') which is native JS, which you are calling on jQuery object, that's why it will not work. jQuery equivalent of this function is .prev('.content')
Correct Syntax would be -
$(".button").click(function() {
if ($(this).parent().prev('.content').css('display') == 'none'){
$('.content').hide();
$(this).parent().prev('.content').show();
}else {
$('.content').hide();
}
});
Working Fiddle
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
My javascript is the weakest of my front-end web knowledge and I assume that's a much more efficient way to achieve my functionality than how I've done it.
Basically, I have a site where you have some <li> items and when clicked they show a particular div and if another div (linked to another <li> item) is currently visible it hides it and shows its respective div. It also assigns an active class to the <li> item to provide a different coloured icon for the active section (standard UX practice).
Here's my HTML and Javascript function.
<li id="general">General</li>
<li id="blog">Blog</li>
<li id="twitter">Twitter</li>
And the javascript (it hurts just looking at it)
$(document).ready(function() {
$("#general").addClass("active");
$("#general").click(function() {
$(".data-tab").hide();
$(".settings-general").toggle();
$("li").removeClass("active");
$("#general").addClass("active");
});
$(".settings-twitter").hide();
$("#twitter").click(function() {
$(".data-tab").hide();
$(".settings-twitter").toggle();
$("li").removeClass("active");
$("#twitter").addClass("active");
});
$(".settings-blog").hide();
$("#blog").click(function() {
$(".data-tab").hide();
$(".settings-blog").toggle();
$("li").removeClass("active");
$("#blog").addClass("active");
})
});
Don't get me wrong it works well! But it just looks exhausting and there's probably a much quicker way jQuery can achieve this. Any advice for a JS beginner?
Just create a single function to accomplish the same thing twice, or you could just loop over the code for each you wish to setup.
function setUp(name){
$(".settings-"+name).hide();
$("#"+name).click(function() {
$(".data-tab").hide();
$(".settings-"+name).toggle();
$("li").removeClass("active");
$(this).addClass("active");
});
}
setUp('blog');
setUp('twitter');
Data-drive the whole thing using data- attributes on the options. The same code then works on any number of items without changes to code:
http://jsfiddle.net/TrueBlueAussie/8hvofd6m/2/
$(document).ready(function () {
$(".menu:first").addClass("active");
$('.settings-general').show();
$(".menu").click(function () {
var $active = $(this);
// Unhilight the inactive items
$(".menu").not($active).removeClass("active");
// Then highlight just the active item
$active.addClass("active");
// Seek the target using a jQuery selector in the data-setting attribute
var $setting = $($active.data('setting'));
// Hide the others
$('.settings').not($setting).hide();
// Show the selected one
$setting.show();
});
});
The data-setting attributes can be any selector, class, id or complex. so you can do cool stuff like:
<li class="menu" data-setting="#info .subinfo:first">First info</li>
You can set a single class on a parent container and use css to hide the elements, something like:
<style>
div.tab { display: none }
body.general li.general { font-weight: bold; }
body.general div.tab.general { display: block; }
body.blog li.blog { font-weight: bold; }
body.blog div.tab.blog { display: block; }
body.twitter li.twitter { font-weight: bold; }
body.twitter div.tab.twitter { display: block; }
</style>
<body>
<ul>
<li class="general">General</li>
<li class="blog">Blog</li>
<li class="twitter">Twitter</li>
</ul>
<div class="general tab">general tab</div>
<div class="blog tab">blog tab</div>
<div class="twitter tab">twitter tab</div>
<script>
$('li').click(function () {
$('body').attr('class', $(this).attr('class'));
});
</script>
</body>
See http://jsfiddle.net/szzdyp1n/ for a working example.
I'm not looking for accordion functionality, but the ability to toggle multiple states when a single element is clicked. I thought this would be extremely simple, and it is. The code simply isn't working. Can anybody take a look at the code and suggest something I might try?
$(document).ready(function(){
$("#nav_header").click(function(){
if (desktopNavigation === 0) {
$("#navigation").css("overflow","hidden");
$("#navigation").css("height","0px");
desktopNavigation = 1;
}
else if (desktopNavigation === 1) {
$("#navigation").css("overflow","visible");
$("#navigation").css("height","auto");
desktopNavigation = 0;
}
else {
}
});
});
The initial value for the variable is as follows:
var desktopNavigation = 0;
The HTML I am trying to effect is in a page with jQuery loaded, and is as follows:
<div id="nav_header" class="trigger">
<ul>
<li>NAV MENU #1 Title</li>
<li>NAV MENU #2 title</li>
<li>NAV MENU #3 title</li>
<li>NAV MENU #4 title</li>
<li>NAV MENU #5 title</li>
</ul>
</div><!--close nav_header-->
<div id="navigation" class="target" style="height:0;overflow:hidden;">
<div id="nav_column">
NAV MENU #1
</div><!--close nav_column-->
<div id="nav_column">
NAV MENU #2
</div><!--close nav_column-->
<div id="nav_column">
NAV MENU #3
</div><!--close nav_column-->
<div id="nav_column">
NAV MENU #4
</div><!--close nav_column-->
<div id="nav_column">
NAV MENU #5
</div><!--close nav_column-->
</div><!--close navigation-->
It may also be pertinent that I am executing this code on a wordpress page, and that it worked perfectly on my local environment.
Your question is lacking context. What does "the code simply isn't working" mean? Where is "desktopNavigation" define? What exactly does "toggle multiple states" mean?
Going off assumptions, people can't give a direct, concise, answers. With that being said, here is an example which hopefully answers your question:
JSFiddle: http://jsfiddle.net/seibert_cody/mk6juczp/1/
HTML:
<div>
<div id="nav_header"></div>
<ul id="navigation">
<li>I</li>
<li>Am</li>
<li>Iron</li>
<li>Man</li>
</ul>
</div>
JS:
$(document).ready(function(){
var state = 0;
var navClassMap = ["red_state", "blue_state", "green_state", "hidden_state"];
// Each click will increment the class of the UL thus toggling multiple states
$("#nav_header").click(function(){
var $navigation = $("#navigation");
// remove the current class
var curClass = navClassMap[state];
$navigation.removeClass(curClass);
// Increment to the next class (loop back to start on overflow)
state = (state + 1) % navClassMap.length;
// Add the new class
var nextClass = navClassMap[state];
$navigation.addClass(nextClass);
});
});
CSS:
#nav_header{
width: 100%;
height: 50px;
background-color: #ef102f;
cursor: pointer;
}
#nav_header:hover{
background-color: #Ff402f;
}
.red_state{
color: red;
}
.blue_state{
color: blue;
}
.green_state{
color: green;
}
.hidden_state{
display: none;
}
From within the code you provided its not clear what the var desktopNavigation initially is, so it will never be === 0or 1.
$(document).ready(function(){
var desktopNavigation = desktopNavigation || 0;
$("#nav_header").click(function(){
if (desktopNavigation === 0) {
$("#navigation").css("overflow","hidden");
$("#navigation").css("height","0px");
desktopNavigation = 1;
}
else if (desktopNavigation === 1) {
$("#navigation").css("overflow","visible");
$("#navigation").css("height","auto");
desktopNavigation = 0;
}
else {
}
});
});
or write:
...
if (desktopNavigation === 0 || !desktopNavigation) {
...
Above your click function, add:
var desktopNavigation = 0;
desktopNavigation is probably undefined.
But if your goal is to hide a div may I suggest using the built in jQuery function .toggle()
$("#navigation").toggle();
Or if you want to toggle multiple, more extensive styles use .toggleClass() to add or remove a custom class.
$("#navigation").toggleClass('hidden');
By "local environment", do you mean you have a wordpress environment set up on your local machine? If the changes are working on your local and not on your remote, I would try:
Clearing your browser's cache and refresh the remote environment
Inspecting the #navigation element using chrome "inspect element" and make sure it doesn't contain any extra css which may be hiding the #navigation
Print to the console when the #nav_header is clicked; this is to make sure the click callback is working as intended
Check to make sure there isn't another element consuming the click which is wrapping #nav_header
One thing I will also note is that you define id="nav_column" multiple times; you shouldn't be using more than one instance of the same ID.
Good luck
Thanks for the suggestions, they're all viable and work just fine. The problem was with Jquery itself.
This must have been a Wordpress thing, but when I changed the version of Jquery that enqueued, everything worked. It worked on my computer outside of wordpress, but as soon as I put it up live, none of the Jquery functions worked.
I changed it from 1.2.1 to 1.11.0. I thought it would be backward-compatible, but it seems like I have a lot to learn about Jquery.