jQuery click function using same classes - javascript

I have a dropdown function that I need to work only on the div clicked, not all (I have 14+ of the same classes on the page that need to be displayed when a certain one is clicked)
At the moment my jQuery is as follows.
$('.qacollapsed').hide();
$('.qa').click(function () {
$('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Of course, that is toggling all qacollapsed classes when there is 14 on the page (Q&A)
Is there a way for it to only drop down the one that is clicked?
the HTML
<div class="qa">
<h4 class="question"> </h4>
</div>
<div class="qacollapsed">
<p> </p>
</div>

It would be helpful to provide a snippet of HTML here, but I'll take a guess at the structure of your markup for now..
Instead of referencing all .qacollapsed elements, you need find elements that are close to the .qa that was clicked, e.g.:
$('.qa').click(function () {
$(this) // start with the clicked element
.find('.qacollapsed') // find child .qacollapsed elements only
.slideToggle();
$(this).toggleClass('active');
});
This will work if .qacollapsed is inside .qa - if not, you might need to use next (for siblings), or one of the other jQuery tree traversal methods.

Yo could find() it or use this as a context in the selector to choose only a descendent of the clicked object
$('.qa').click(function () {
$('.qacollapsed', this).slideToggle();
//You could do $(this).find('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});

Check out the jQuery selectors and why not just use $(this)?

$('.qacollapsed').hide();
$('.qa').click(function () {
$(this).toggleClass('active').next().slideToggle();
});

Personally, I'd give all the divs IDs, the clickable bit being the ID of the question in the database for example, and the answer just being id='ID_answer' or something, then use jquery to slide in the div with the id corresponding to the link clicked, ie
Var showIt = $(this).attr('id') + '_answer'
$('.qacollapsed').not('#'+showIt).hide();
$('#'+showIt).slideToggle;
That will hide all the divs without that ID and show the required one.
Dexter's use of .next above looks simpler though, I've not tried that as being relatively new to jquery too.

Related

jQuery.toggle() not working on a div

On a web page we have a list of profiles. On the right hand side of the profile is some text, followed by an arrow img#arrow.
When img#arrow is clicked, we have the following jQuery we hope to run:
However, the corresponding .bottom-sec is not toggling.
jQuery('#arrow').click(function(){
var $parent = $(this).parent();
$($parent).addClass('active');
jQuery($parent +' .bottom-sec').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="profile-right">
<h2>Bob Brown</h2>
<h3>Non-Executive Chairman</h3>
<p>Intially showing text.</p>
<div class="bottom-sec" style="display: none;">
<p>Initially hidden text.</p>
</div>
<img id="arrow" src="/wp-content/themes/wtc/images/icons/down-arrow-circle-hi.png">
</div>
Problem
The problem with your code is exactly what the comment on your question is saying, but he didn't explain anything:
You're combining two different ways of selecting elements. One is with selectors, the other is traversing. You're using them in a way which isn't possible (the $parent + ' .bottom-sec' part). The comment linked to a jQuery page about traversing which you should definitely read! It tells you a lot about how to use traversing functions, which you could use!
Solution
There are multiple solutions to this, but I'll write down the one I think is the best:
First of all, change the HTML a bit. I've removed the element style of .bottom-sec and changed the id of the image to a class, because you have multiple images with the same id on the page, which is not a recommended thing to do. Classes can occur more than once, id's cannot.
<div class="profile-right">
<h2>Bob Brown</h2>
<h3>Non-Executive Chairman</h3>
<p>Intially showing text.</p>
<div class="bottom-sec">
<p>Initially hidden text.</p>
</div>
<img class="arrow" src="/wp-content/themes/wtc/images/icons/down-arrow-circle-hi.png">
</div>
I've reduced the JavaScript to the following. Note that is just reduced to one line, where a click on the .arrow element goes searching for the closest .profile-right parent. If, for whatever reason, you decide to change the HTML and the .arrow element is no longer a child of the .profile-right, this code still works. The only thing it does is toggle an active class on the .profile-right.
jQuery(document).on('ready', function() {
jQuery('.arrow').on('click', function(){
jQuery(this).closest('.profile-right').toggleClass('active');
});
});
The document ready listener was added because of OP's comment.
With CSS, we can use the new .active class to show or hide the element.
.profile-right .bottom-sec {
display: none
}
.profile-right.active .bottom-sec {
display: block
}
Original Code Fix
If for some reason you wanted to use your original code, this is how it should be:
// Nothing wrong about this part.
// Your only worry should be that there could be
// multiple elements with the same ID, which is something really bad.
jQuery('#arrow').click(function(){
// This part is correct, no worries
var $parent = $(this).parent();
// Removed the $(...), because $parent is already a jQuery object
$parent.addClass('active');
// Changed the selector to a find function
$parent.find('.bottom-sec').toggle();
});
You could also combine all of the code inside the listener function to just one line:
jQuery('#arrow').click(function(){
$(this).parent().addClass('active').find('.bottom-sec').toggle();
});
Change your js code like below.
jQuery('#arrow').click(function(){
var $parent = $(this).parent();
$($parent).addClass('active');
jQuery($parent).find('.bottom-sec').toggle();
});
In your event listener you can catch the element (the down arrow) that triggered the event. It will be referred as this.
Then you can go through the DOM tree using .next() and .parent() to access the <div> to toggle.
Note: you may need more functions than the one I explained above.
Note 2: without code or more detailed information, we can't help you further, I will edit this answer if you add details.

Function for adding and removing style on click and unfocus

I am trying to implement a function which changes style of element on click and remove it when unfocus. For ex: When element2 is clicked, it should remove class of other elements, and add class to the clicked element only.
<div class="dope" id="element777"></div>
<div class="dope" id="element2"></div>
<div class="dope" id="element11"></div>
<div class="dope" id="element245"></div>
<div class="dope" id="element60"></div>
.....(More are created automatically, numbers are not estimatable)
I couldnt know the element ids that are created. The only remains same is class.
I have tried this, but its an unprofessional approach.
$('#element1').click(function(){
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element1").blur(function(){
$("#element1").removeClass(dope);
});
$('#element2').click(function(){
$("#element2").addClass(dope2);
$("#element1").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element2").blur(function(){
$("#element2").removeClass(dope);
});
What is the best approach for automating this function, instead of adding click and blur (unfocus) function to ALL of elements ?
You can listen for click events on any div with an id containing the word "element', then target its siblings elements (those that are not clicked, without referring to them by id). This might do it:
$("div[id*='element']").click(function(){
$(this).addClass('dope').siblings('.dope').removeClass('dope');
});
Your jQuery could be vastly simpler if you leverage this and siblings:
Instead of:
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
It could be:
$('.dope').click(
function() {
$(this).addClass(dope2).siblings().removeClass(dope);
}
);
NOTE:
Do you have a variable called dope with the class name, or is dope the class name? If it's the classname, you need to put it in quotes: $(this).addClass('dope2'), etc.
If you are removing the class dope, then will want to add a class you can always use to select these elements (so that when you remove dope, it continues to work).
Button part:
$("div").click(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).addClass("dope2");
$(".dope").not($(this)).removeClass("dope");
}
})
Blur part:
$("div").blur(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).removeClass("dope");
}
}
I would recommend using the :focus css selector rather than using javascript to do what you are doing... Read more here. Instead of having a click listener, the focus selector will take care of that for you and automatically remove the styling when the element is out of focus.

Find element above another using jQuery

I'm trying to find the element using jQuery from the following html.
<ul class="gdl-toggle-box">
<li class="">
<h2 class="toggle-box-title"><span class="toggle-box-icon"></span>Volunteer Form</h2>
<div class="toggle-box-content" style="">
</div>
</li>
</ul>
What I'm looking to do is when the h2 is clicked find the li above the h2 add a class active to it. Tried a few different calls but no luck.
EDIT
The biggest issue is that there are multiple toggle boxes on a page so something like this works on pages with a single toggle but pages with multiple the result is they all open together.
var gdl_toggle_box = jQuery('ul.gdl-toggle-box');
gdl_toggle_box.find('li').each(function(){
jQuery(this).addClass('item');
});
gdl_toggle_box.find('li').not('.active').each(function(){
jQuery(this).children('.toggle-box-content').css('display', 'none');
});
gdl_toggle_box.find('h2').click(function(){
if( jQuery('.item').hasClass('active') ){
jQuery('.item').removeClass('active').children('.toggle-box-content').slideUp();
}else{
jQuery('.item').addClass('active').children('.toggle-box-content').slideDown();
}
});
You can use closest.
closest will match the first parent element that matches the selector traversing up the DOM tree.
Demo
$('h2.toggle-box-title').click(function(){
$(this).closest('li').addClass('active');
});
Try this.
$('h2.toggle-box-title').click(function(){
$(this).parent().addClass('newclass');
});
try this:
$('h2.toggle-box-title').click(function() {
$(this).parent('li').addClass('active');
});
On you click in the button you can use the event:
$("something").parent().find("h2.myClass");
// And if you want you can add class after you find you object
http://api.jquery.com/find/
Selecting an element's parent
In order to select an element parent, you can use the parent() function.
Try this:
$('h2.toggle-box-title').click(function() {
$(this).parent('li').addClass('active');
});
*to be more specific, you target the parent you would like to choose by specifying its selector
Check the jQuery API Documentation here
parent() - Get the parent of each element in the current set of matched elements,
optionally filtered by a selector.

Using javascript on multiple Div Id's

I have created an expanding div that hides on load and expands when clicked using javascript and jQuery. My problem is that I need to use this feature multiple times on each page (10-30x). Is there a way to call the function to work with multiple Div ids using an array or something of that nature (I am a newbie, my apologies), e.g. a few of my div ids would be eb1, eb2, eb3, eb4. and here is my script that currently works on one id:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#eb1').hide();
//hides box at the begining
jQuery("#hide").click(function() {
jQuery('#eb1').fadeOut(300);
//jQuery('#the_box').hide();
});
jQuery("#show").click(function() {
jQuery('#eb1').fadeIn(300);
//jQuery('#the_box').show();
});
});
</script>
Any help would be appreciated, even a link to an explanation.
Thanks,
Travis
Further to John Conde's answer this is also possible using attribute-starts-with:
jQuery('div[id^="eb"]').hide();
JS Fiddle demo.
It is, of course, easier to just use a particular class-name, and the selector then becomes:
jQuery('.className').hide();
JS Fiddle demo.
References:
Attribute-starts-with ([attribute^="value"]) selector.
You should be able to do this by separating the ids with a comma:
jQuery('#eb1','#eb2','#eb3').hide();
just type "jquery multiple div show hide" into google:
the first link gives this:
Show/Hide Multiple Divs with Jquery
:)
Maybe it is cleaner to add a css class to all the div (or whatever tag you use) elements that should behave like that, then use that class in the selector ?
jQuery('div.hidable').hide();
//hides all 'hidable' boxes
jQuery("#hide").click(function() {
jQuery('div.hidable').fadeOut(300);
});
etc...
You could create a function to do that.
let me explain
function ToogleDiv(container){
// simple toogle
$(container).toggle();
// a toogle with some effect
$(container).toggle('slow', function() {
// add some action }); }
here's is a Jquery example Toogle Jquery Example
Hope this helps.
You can use Attribute Starts With Selector [name^="value"]
var divs = $('div[id^="eb"]');
$(divs).hide();
$('#show').click(function(){
$(divs).show();
});
$('#hide').click(function(){
$(divs).hide();
});
Live example on JSFiddle
function show(var id){
jQuery(id).fadeIn(300);
}
function hide(var id){
jQuery(id).fadeOut(300);
}
and then, in your divs:
<a id="hide" onClick="hide('eb1')">hide</a>
<a id="show" onClick="show('eb1')">show</a>
<div id="eb1"></div>

jquery toggling a div - how to do this with multiple ids?

I am new to Jquery. My setup is as follows:
I have a series of divs that need to be able to be toggled (display hidden and shown). Each div has an action that can be performed so a unique ID will be necessary to know from which div the event came from.
To toggle the div I have a button for each div (which is not located within the div to be toggled).
Right now without jquery, I use the button's onclick event to pass the ID of the corresponding div to be toggled. Using the unique ID I can do the following:
function toggleFlag(divId) {
var div = document.getElementById(divId);
div.style.display = (div.style.display=="block" ? "none" : "block");
}
divId is unique so I also know where the event comes from if action within the div is performed.
the anchor code looks something like this:
onclick="toggleFlag('id-111');"
where the '111' is the unique id
First off, is it even worth it to use jquery for this if the extent of my javascsript isn't much more complicated (aside from maybe simple ajax).
More importantly, how would this properly be done using jquery?
Update: I am very close to solving this. I managed to get it to work using one of the suggestions below requiring unique class names for each button. A couple of the methods suggest implementations where the class name is the same for all buttons (I want this in order to be able to statically assign styles to the button class), but I could not get these to work. Could somebody please elaborate on the solution? Thanks!
Let's say that you build your anchors to have an id that corresponds with the id of the DIV to toggle and further that they all have a common CSS class. For example,
Toggle
<div id="d_111">Some stuff.</div>
Now you could use jQuery to build the click handlers for all of these pretty easily.
$(function() {
$('a.toggleButton').click( function() {
var divId = $(this).attr('id').replace(/a_/,'d_');
$(divId).toggle();
});
});
You could do something like this:
HTML:
<button id="btnId1" class="divId1" value="Click me to toggle divId1"/>
<button id="btnId2" class="divId2" value="Click me to toggle divId2"/>
etc...
<div id="divId1">div 1</div>
<div id="divId2">div 2</div>
etc...
SCRIPT:
$(function() {
$("button").click(function() {
var divId = $(this).attr("class");
$("#" + divId).toggle();
});
});
This approach has the advantage of only defining the event once for all buttons. You could also use another strategy for storing the div id in the button information, like a non-standard attribute - which jquery can pick up as well, or make the div id a part of the button id like so:
<button id="btn_divId1" value="Click me to toggle divId1"/>
<div id="divId1">div 1</div>
and then extract the id of the div from the id of the button clicked (personally this is the approach I'd take)
Hope this helps
EDIT: To answer the first question, yes you would benefit from doing this with jQuery since it would shorten the amount of code that you are writing and it would allow you to move to unobtrusively assigning events to the buttons which is a good thing :)
EDIT 2: Using non-standard attributes:
HTML:
<button id="btnId1" divid="divId1" class="btnToggle" value="Click me to toggle divId1"/>
<button id="btnId2" divid="divId2" class="btnToggle" value="Click me to toggle divId2"/>
etc...
<div id="divId1">div 1</div>
<div id="divId2">div 2</div>
etc...
SCRIPT:
$(function() {
$("button").click(function() {
var divId = $(this).attr("divid");
$("#" + divId).toggle();
});
});

Categories

Resources