I want to add a slide up affect with jQuery to a DIV when a link inside of the DIV is clicked, but the problem i am running into is the class of the DIV's are defined by a loop. So, i can't define the DIV class in the jQuery line, because each DIV class is different and i cannot determine ahead of time what they are. I am trying to use .parent and .child but I am not sure how to go about this. Is this making any sense?
Bind to the click of the element you want (in this case I just used a simple anchor element). Then find the first parent that is a div and perform the slideUp() effect.
$('a').click(function() {
$(this).parents('div:first').slideUp();
});
You can see it work here: http://jsfiddle.net/XNnSp/
Let me know if that's what you are looking for http://jsbin.com/ehoza3
$('a').click(function() {
$(this).parent().slideUp();
});
Two (most obvious) ways
FIRST
If your tree is always defined in terms of depth you could access your parent DIV doing just that:
$(this).parent().parent().parent().slideUp();
SECOND
Add an additional class that doesn't clash with dynamic ones and do this:
$(this).closest(".some-custom-class").slideUp();
Related
In my example here:
Example
JS
$('button').on('click', showHide);
$('.overlay').on('click', showHide);
function showHide(){
$('.scroll-container').toggleClass('show');
$('.content-container').toggleClass('no-scroll');
$('.overlay').toggleClass('opacity');
}
you have a basic body with text. A clickable element (in this case a 'button') causes a scrollable container to appear and 'hover' over the original body, which can be hidden again by clicking outside of this container.
I'm not very good at JavaScript and with this example I was helped by a friend. The thing I'm struggling with now is that I need multiple different clickable elements, displaying a similar scrolling container, but with different content.
I'm doing this for a portfolio website, so imagine a bunch of photos on a page, which when clicked result in a body hovering over the original content, further elaborating the clicked project.
Do I create multiple id's for each project, together with multiple scrolling container id's, and just copy the JavaScript a couple of times?
I hope this makes sense and I hope someone is capable of explaining to me how I'm able to create the proposed effect.
First of all, you have to make a connection between buttons and containers that should be opened. One way is to use their indexes, so that when first button is clicked, first container would open. You can use this reference of the clicked object inside your function, in order to get its index. Like this:
$(this).index()
Then, you have to select all the elements with scroll_container class $('.scroll-container') and reduce the set of matched elements to the one by passing index of the clicked element to .eq() method .eq($(this).index()). Finally, you have to add show class to it addClass('show').
And because the logic is changed, you have to separate actions done on button and .overlay click events. They do not make a reverse action now, so they are not "togglers" anymore.
http://codepen.io/anon/pen/LpWwJL
$('button').on('click', show);
$('.overlay').on('click', hide);
function show(){
$('.scroll-container').eq($(this).index()).addClass('show');
$('.content-container').addClass('no-scroll');
$('.overlay').addClass('opacity');
}
function hide() {
$('.scroll-container').removeClass('show');
$('.content-container').removeClass('no-scroll');
$('.overlay').removeClass('opacity');
}
UPDATE
One thing you should keep in mind regarding $(this).index() method.
As it is written here:
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
That means that trigger elements should have common parent in order to maintain our logic.
In cases like this: https://stackoverflow.com/posts/32946956/edit, elements that are triggering scroll_container appearance, have different parent nodes (they are placed in 3 different divs). So, if we will call index() method for each of them, it will return '0' because they are the first and the only elements in their parent nodes.
Actually it means that you have to get the order of their parent elements, not theirs own. This can be achieved by using parent() method before index():
$(this).parent().index()
Here is updated codepen.
If I were you, I would implement a generic function to display a different content using the same function based in the button. So for that we will need something to relational the click with the content for that we can set a value in out button:
<button data-id="1">Click me 1!</button>
<button data-id="2">Click me 2!</button>
so out when we click the button we should get the value to send it to our function:
$('button').on('click', function(){
var dataButtonValue = $(this).data('id');
});
Then we can match it with the content using for example data-content-id
<div class="content" data-content-id="1">your wording</div>
<div class="content" data-content-id="2">your wording</div>
With all that we can manage what content we want to show depends on the click.
function showHide(id){
$('.content[data-content-id="' + id + '"]').toggleClass('show');
}
DEMO
I hope it's helps.
I'm working on a simple website to use at a conference and I'm looking for some help understand the implications of two ways to achieve an effect:
Using .toggle() to show or hide content
This is the method I started with because it is an intuitive action to tap an element to have it's content appear. However, a problem arises when I try to limit one open div at a time.
Summary I'm having trouble limiting the number of opened elements.
Applying an active class with jQuery
Using this method, I can display the hidden content by selecting the child element (see code below), but this stops the user from closing the content by tapping it again. Because I'm expanding divs horizontally, this isn't ideal because of the scroll space that's added.
Summary: How do you close the active div on a second click with this method?
CodePen Demo - Staged site
Relevant Code
This method is using CSS to apply the active class. It works, but like I said above, I'm having a hard time removing the active class from an element tapped again. Use the demo linked above to see how the toggle action works on the page (uncomment lines 8 and 9).
$(".title").click(function() {
//remove active class from other elements
$('.post').removeClass('active');
// Bind to the div
$post = $(this);
// Set active class on .post to control scroll position
$post.parent().toggleClass('active');
// Toggles the hidden .content div
//$post.next().toggle(250);
$('html, body').animate({scrollLeft: $('.active').offset().left},500);
});
The accompanying .active CSS:
.post .content {
display:none;
}
.active {
margin-top:-120px;
}
/* Shows the content div rather than toggling with jQuery */
.active > .content {
display:block;
}
Is there a way I can allow both behaviors (tap to open/close, one open div at a time)? Which method is best suited for that?
You certainly can use toggle() while hiding the other ones. Try something like this:
$(".title").click(function() {
$('.post').not($(this).parent()).hide();
$(this).toggle();
$('html, body').animate({scrollLeft: $(this).parent().offset().left},500);
});
Update: changed .not(this) to .not($(this).parent()) as .title is always child of .post.
Slightly optimised version of #Daniel's solution
$('.title').click(function() {
var clickedPost = $(this).parent('.post')
clickedPost.toggle().siblings('.active').hide();
$('html, body').animate({scrollLeft: clickedPost.offset().left},500);
});
Local var: If you access this, or any other DOM element more than once inside a scope, it's always more efficient to assign it to a local var than wrap it in a JQ object multiple times.
SIblings selector: I don't have a benchmark for this, but running a selector on a subset of the DOM rather than the whole DOM seems intuitively faster. This is more best practice than a large performance hit, but all the little functions add up too.
Chaining JQuery functions: Most JQ functions that act on a JQ element return that element. I can't say that this is more efficient but it's certainly more concise, but this all depends on personal preference.
With very little code you can do this with toggle.
$(".title").click(function() {
$(".post").hide();
$(this).children(".post").toggle();
});
I made it as simple as possible to show the functionality which you could then extend on.
Here is a jsfiddle
EDIT update after comment
I have edited it to now only show 1 at a time and if the 1 currently being shown is clicked it hides it
I also elected to use slideUp() and slideDown() as it seemed to better suit your needs
$(".title").on("click", function(){
if($(this).children(".post").is(":visible")){
$(this).children(".post").slideUp();
}else{
$(".post").not($(this).parent()).slideUp(500);
$(this).children(".post").slideDown(500);
}
});
updated jsfiddle
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
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
I have a site I am designing that has some nested DIV elements that I use as containers to hold expandable buttons.
The user clicks on a button and it expands to expose some more content.
Everything works great until I have a DIV that is inside of a parent DIV with it's display property set to "none".
Is there any way to force the jQuery .slideUp() method to minimize the expandable buttons regardless of whether it is in a display:none parent or not?
OR, what property/properties do I need to set to make $.slideDown() work properly on an element that was setup up in a display:none parent DIV?
If the parent has display:none; then you'll need to show it before trying to slideUp the child. You can do this with the show function.
$(divToSlide).parent().show();
$(divToSlide).slideUp();
Per the comment, you could alternatively, you could just set the display property to 'block'
$(divToSlide).parent().css("display", "block");
$(divToSlide).slideUp();
Instead of applying slideUp() to the expandable buttons, try setting their "display" value to "none".
This way, when you apply the .slideDown() method it will think that element has already been hidden using the .slideUp() method.
I had the exact same problem and none of the mentioned solutions worked for me the way I expected, as sometimes I lost the slideUp/slideDown animation itself when applying the show() function. My final solution was using a callback function to apply the style directly:
$(divToSlide).slideUp(delay, function () {
// When animation ends
$(this).css('display', 'none');
});
This way I could get the same result without losing the animation.