How do I hide an element with the same markup via jquery? - javascript

I have two custom dropdown lists that have the same markup. I need to have only one show at a time. Right now, I'm able to open both at the same time. Both should also close when I click off the list.
The same markup for both lists is required, so I can't use unique ID's or additional classes to make this happen.
Here is a link to my fiddle example: http://jsfiddle.net/dg7Lc/29/
Any help would be greatly appreciated, thanks!
-D

Consider adding a data attribute such as 'active' via jquery when you click on one of them, then hide all those that have that attribute.

$('.custom-select').eq(0).hide() will hide the first one.
Use .show() instead of .hide() to show (obviously) and change the index to (1) to get the second one.

First thought would be if you could wrap a span or div around either or both and use that to get around the "same markup" limitation. Other than that, though, I'd suggest using order in page - use .next() and .prev() to get between them, and something like
$("div.custom-select").get(0)
or
$("div.custom-select").get(1)
to select them from outside.
edit: if you can run them off of something like an onmouseover, onchange, or whatnot, it's even easier - the one that's changing will be passed into the function as the "this" parameter. Just hide both, and show this, or show both and hide this.
edit2: similarly, once you have one of them hidden properly - well, that one will be hidden, and respond to the ":hidden" selector. Use that to distinguish between them (and save the distinction as a jquery variable) before you go showing or hiding anything else

Hide the first:
$('.custom-select').first().hide();
Hide the second:
$('.custom-select').last().hide();
And then put these lines of code where needed.

http://jsfiddle.net/dg7Lc/31/
Basically, closing the others:
$('.custom-select').not(this).find('ul').slideUp('fast');
And for closing when clicking outside the box, I used this piece of code but it's a bit dirty:
$("body").click(function(e) {
var should = true;
for($e = $(e.target); should && $e.length; $e = $e.parent()) {
should = !$e.is(".custom-select");
}
if(should) {
$('.custom-select').find('ul').slideUp('fast');
}
});

You can bind a click to the document, that looks to see if they clicked on the custom-select or the document outside it and hides any open lists as it should:
$(document).click(function(ev){
if(!$(ev.target).is('.custom-select span')){ $('.custom-select').find('ul').slideUp('fast'); }
});
Updated JSFiddle

Related

Hide elements the correct way

I'm using JavaScript to hide and show some elements onclick events
Using this code
function showPreOne() {
document.getElementById('SecandModalFilter').classList.add('d-none');
document.getElementById('FirstModalFilters').classList.add('d-none');
document.getElementById('colocation').classList.add('d-none');
document.getElementById('coloc-row').classList.add('d-none');
document.getElementById('preFirstModalFilter').classList.remove('d-none');
document.getElementById('FirstModalFiltersa').classList.add('d-none');
}
I don't think this is the correct way! ? specially if I have a very large page with a lot of tabs and elements ?
Thank you
You could add a class on all the element that can be hidden (I assume you are handling a tab system), and just show the one you want to be visible:
function showPreOne() {
document.querySelectorAll('.tab').forEach(elt => elt.classList.add('d-none'))
document.querySelector('#SecandModalFilter').classList.remove('d-none');
}
Otherwise, your current method is not wrong per-say.
If the class is display: none, there's nothing wrong with that approach. Although the code would be more maintainable if you managed the add/remove elements with arrays of ids instead of doing it line by line.
Your approach can be a bit better, if you are showing/hiding elements I suggest you to use the toggle functionnality.
This way you can use only one function that will manage your click event and hide/show your elements, just be sure that the initial state (d-none class present or not) is correct :
function showHide() {
document.getElementById('SecandModalFilter').classList.toggle('d-none');
document.getElementById('FirstModalFilters').classList.toggle('d-none');
document.getElementById('colocation').classList.toggle('d-none');
document.getElementById('coloc-row').classList.toggle('d-none');
document.getElementById('preFirstModalFilter').classList.toggle('d-none');
document.getElementById('FirstModalFiltersa').classList.toggle('d-none');
}
More informations here Toggle specification

how to toggle a div on click at different div?

I am trying to toggle a div by clicking on a different div. The only relation that two divs share is that they are inside the same div. I have a DIV class comment which holds DIV class button that is supposed to toggle DIV class box when clicked. The box DIV is also inside the comment DIV. I am trying to use jQuery(this).find(".box").toggle();, but it is not working. I am triggering it with $( ".button" ).click(function(). The script is currently at the bottom of my body.
Could anyone please tell me what am I doing wrong here? I've been playing around with the function for a while now, but with no luck at all. Thank you in advance for your replies.
JSFIDDLE here
HTML
<div class="comment">
<div class="button">
show/hide .box with text1
</div>
<div class="box">
text 1
</div>
</div>
<div class="comment">
<div class="button">
show/hide .box with text2
</div>
<div class="box">
text 2
</div>
<div>
jQuery
$( ".button" ).click(function() {
jQuery(this).find(".box").toggle();
});
You can use the jQuery selector .siblings() to re-write your function like this:
$( ".button" ).click(function() {
$(this).siblings().toggle();
});
Here's a working fiddle to demonstrate.
All you really need to do is this:
$(this).parent().find(".box").toggle();
In short, change:
jQuery(this).find(".box").toggle();
To ONE of the following lines:
$(this).parent('.comment').find(".box").toggle();
$(this).closest('.comment').find(".box").toggle();
$(this).siblings(".box").toggle();
Full Explanation:
The reason it's not working is due to the call. Let's break down your call and see what exactly it's doing.
First we see a simple jQuery selector. This tells jQuery to look for a div containing the class button. Keep in mind, jQuery makes use of any CSS selector. So selecting an item in jQuery is as simple as using it's CSS selector!
$( ".button" )
Next you are assigning an event. In this case, that event is click, meaning you're telling a div having the class button to do something every time it is clicked. Keep in mind, however, not including a callback function is an easy way to trigger this event as well.
$( ".button" ).click(function() {
Now this next line is where your mistake takes place.
jQuery(this).find(".box").toggle();
The first mistake is the use of jQuery. after you're already making use of it's short sign, $. You only need use the elongated name if you are using jQuery's noconflict because another JS library you include might use $. In other words, if $('.button') works and is a jQuery object when used, then you don't need to use jQuery.. See more about this here.
Now, that aside, we can look at jQuery(this) as $(this). Whenever you use $(this) in an Event's callback method, you're referring to the element that the event was tied too. That means that $(this) in your function refers to $('.button'). The problem here is that you then want it to find an inner element containing the class box. Well according to your HTML, that can't happen since .box is a sibling, it is not within the inner HTML of .button. Thus you need to make a different call before you can find .box.
There are actually several solutions here. No solution is more "correct" than another, just simply different and possibly causes a different amount of "time" to run. Now I went with what I saw as being the most simple in that it gives you control over the parent element which contains ALL relevant elements to this function. I'll talk about possible alternatives in a minute.
$(this).closest('.comment')
The above line simply tells .button:clicked to look for the first parent element that contains the class .comment. In other words, this won't find any children or siblings, it will only go up from the current element. This allows us to grab the block that contains all relevant elements and information and thus make maneuvers as needed. So, in the future, you might even use this as a variable in the function, such as:
$('.button').click(function(e) {
var container = $(this).closest('.comment');
Now you can find anything within this element block. In this case you want to find box and toggle it. Thus:
$(this).closest('.comment').find(".box").toggle();
// Or with our variable I showed you
container.find(".box").toggle();
Now, there are plenty of alternatives based on your HTML layout. This example I've given would be good even if .box was buried inside more elements inside .comment, however, given your exact HTML, we see that .button and .box are siblings. This means that you could make this call different entirely and get the same result using something like:
$(this).siblings(".box").toggle();
This will allow our currently clicked and selected button element to look for ANY and ALL siblings having class box. This is a great solution and simple if your HTML is that simple.
However, many times, for "comment" type setups, our HTML is not so simple, nor is it static. It's usually something loaded after the page load. This means our general assignment of .click will not work. Given your exact HTML and not knowing a static Parent ID, I would probably write your code as:
$(document).on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
What this does is allow for this click event to be assigned to ANY element containing .button for a class, whether loaded with page or even ten minutes after the page is up. However, the caveat often seen here is the assignment is placed on document. Should we assign a lot of events to document it could become quite convoluted and possibly slow down the client's browser. Not to mention the arguments held over all the other headaches this could cause. So here's my recommendation, make a static (loads with page, is a part of page's main HTML) loading area and do our dynamic assignment to that. For instance:
<div id"Comments"><!-- load comments --></div>
Then you can do the assignment as such:
$('#Comments').on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
If you have any more questions, just comment!
Side Note .on is for jQuery versions 1.7+. If using older jQuery, use .live or .bind

jquery "hasClass()" not working?

I need to hide a div if another div has a class.
I've created a very basic example HERE
I need the div on the bottom to hide when the word "click" is.. well.. clicked. It adds a class to the middle div just fine, but it seems hasClass() doesn't want to work?
NOTE: The structure needs to be like this. If "click" is clicked, modify the middle div (add class?), and manipulate the bottom div based on the middle div. With this setup - I can't just do "if CLICK is clicked, slideUp() the bottom div".
Also, once "ok" or "cancel" is clicked, it will revert, because the middle div will no longer have the class. Provided that's the method I can get working here, haha.
your if statement is outside of any function, so there is no reason for it to be called after the script is loaded.
See this fiddle, I think that's what you want.
On a side note, another variation to check if there's a class is:
if ( $('body.className').length ) {
Still recommend hasClass though. Just nice to see variation sometimes.
This is only getting called once, when the script loads. You need to have make sure it gets called in your .click(...) handler.
if($('#timestampdiv').hasClass('hidepub')) {
$('#major-publishing-actions').slideUp('slow');
}
As mentioned by others, you don't have a call to if on all click event handlers. Create a custom function with statement inside if and call it on all click handler.
Check this fiddle
After you append the class to the DOM element, this should properly hide the element.
$('.element').click(function()
{
$('.thisElement').addClass('hidepub');
if($('.thisElement').hasClass('hidepub')) {
$('.thisElement').hide();
}
});
You can combine them all into one function - And you want that check to be inside the click functions
You can reduce the addclass removeclass by using toggleClass and passing in a condition
$('a.edit-timestamp,a.save-timestamp,a.cancel-timestamp').click(function() {
var $tsdiv = $("#timestampdiv");
// add class showpub if edit is clicked
$tsdiv.toggleClass('showpub',$(this).hasClass('edit-timestamp'));
// add class hidepub only if it wasn't edit that was clicked
$tsdiv.toggleClass('hidepub',!$(this).hasClass('edit-timestamp'));
// then do your toggle
if ($tsdiv.hasClass('hidepub')) {
$('#major-publishing-actions').slideUp('slow');
}else{
$('#major-publishing-actions').slideDown('slow');
}
});
http://jsfiddle.net/JPcge/
You can reverse it by swapping the logic passed into the toggleClass() methods

Div display based on radio selection

Currently I have a piece of code that works fine as long as there are no other divs in the page. If I add other divs, they will close upon any radio selection. I just need a simple modification to the code to open and close without closing all other divs. The working example can be seen here.
http://jsfiddle.net/L5qfn/38/
I added the "wrapper" to the entire contents of the body to demonstrate how everything closes. Take out the wrapper...and things work like I want it to. Any suggestions?
The problem comes from your <div id="wrapper">, and this line :
$('div[class!="formset"]').slideUp("fast"); //Slide Up Effect
I rather suggest to change it to :
$('div .sub-formset').slideUp("fast"); //Slide Up Effect
See the result : http://jsfiddle.net/L5qfn/40/
The problem is caused by the following line:
$('div[class!="formset"]').slideUp("fast");
That basically says "hide any div which does not have the class formset". The wrapper div does not have that class, so it gets hidden. I'm not sure what that line is doing (it appears to do nothing useful in the fiddle at least) so I'd suggest just removing it, unless you can expand upon your problem.
Here's an updated fiddle.
Update based on comments
As #fflorent has mentioned, it looks like you actually wanted to hide .sub-formset, so you probably want to change that selector to:
$(".sub-formset").slideUp("fast");
Note that I've used a class selector (the . character) rather than using an attribute equals selector as you've done in your fiddle.

How to make function work after append

For example i'm using append, and for example i'm appendig button in to a div, and i have function $('button_id').click(... etc to work affter i append the div, how can i do that.I mean i get no errors, but the function is not starting, it's because i append and then i want to use the function but how to do that, i tryed with delegate, but same thing.I tryed with function in the button tag , onmouseover and then the function thing, but nothing it gives me function not found.What is the solution ?
I have two events, one event is click event that appends button, the other event is click event that does something if the button that was appended is clicked, but that second event is not working ?
Try using :
$(elem).live(...)
It will bind event for now and in the future.
Firstly, it always helps if you show us the exact source code. $('button_id') is the incorrect selector to start with, try something more along the lines of $('#button_id') as your selector. Also, are you appending dynamic content? Anyways, I've always used the delegate() function quite successfully, but have you tried using the live() function? Also, one more thing to make sure of is that you have the newest version of jQuery as your source.
As was stated as well, you can not have duplicate ids, if you want to have a pointer, use class, instead of id="some_id" use class="appended". To select those using jQuery, use the selector like this $('.appended').
Try something like this it will work as per your expectations.
$("#button_id").click(function(){
//On click code goes here
}).appendTo($("#div_id"));
It's difficult to determine the problem you're having without seeing your code, but delegate (or live) should be perfect for what you're trying to do:
$("body").delegate("#b", "click", function() {
alert("ok");
});
$("#example").append('<input type="button" id="b" value="Click" />');
The click handler above will fire when an element with id="b" is clicked, whether or not that element happens to be in the DOM right now or not.
However, as others have noted, it's important to remember that IDs need to be unique within a document, so by the sounds of it you may be better of using classes instead.
You can see an example of the above code running here.

Categories

Resources