Fadeout all nested divs - javascript

On my page I'm trying to do smth like that: Lets say, when we click on some link with id min_reg it animates div with idftr_form_cntr, and shows another div tcr_form_cntr within.
There are 3-4 links that does same function but shows another div within ftr_form_cntr. Well if user clicked one of this links for the first time then there is no problem. But if user already clicked (I mean if ftr_form_cntr already opened) I want to just fadeOut all existing divs nested to ftr_form_cntr and fade in one another div (or swap existing div with another one).
Take a look at this line tcr_form_cntr.fadeIn(1000). What do I need to do before this line to fadeOut all nested divs?
My function look like this:
$(min_reg).click(function () {
if($(ftr_form_cntr).hasClass('opened')){
$(ftr_form_cntr)...<fadeOut all nested divs>
tcr_form_cntr.fadeIn(1000);
return;
}
ftr_form_cntr.show().stop(true, true).animate({
height:"170"
},1000).addClass('opened');
tcr_form_cntr.fadeIn(1000);
});

Assuming that ftr_form_cntr is a string variable holding the jQuery selector for your container element, you can select all the div elements inside and fade them like this:
$(ftr_form_cntr + " div").fadeOut();
Have a look at the jQuery doco on selectors, specifically the "descendant selector".
If ftr_form_cntr is not a string variable but is actually, say, a reference to a DOM element or something then another way to select certain nested elements is using the .find() method, which gets descendants of the elements in your existing jQuery object according to another selector you provide:
$(ftr_form_cntr).find("div").fadeOut();

Your function could look like this:
$(min_reg).click(function () {
var animated_div = $(ftr_form_cntr);
if(animated_div.hasClass('opened')){
animated_div.find('div').fadeOut();
tcr_form_cntr.fadeIn(1000);
return;
}
animated_div.show().stop(true, true).animate({
height:"170"
},1000).addClass('opened');
tcr_form_cntr.fadeIn(1000);
});
What I did is:
I cached the element you work on ($(ftr_form_cntr)),
used .find() jQuery method to get all the divs you want to fade out,
Did it help? Please make sure that both ftr_form_cntr and tcr_form_cntr are defined and first is eg. selector, but the second must be jQuery object.

Related

Cannot select all elements except one

I am trying to select all the elements of a page except one, inside a function:
$('#sidebutton').click(function () {
if (!$('.sidemenu').hasClass("current")) {
prevScrolPos = $(window).scrollTop();
scrollTo = 0;
} else {
scrollTo = prevScrolPos;
}
$('.hidelem').toggleClass("hidden");
$('.sidemenu').toggleClass("current");
$('html,body').scrollTop(scrollTo);
});
It works when I use a simple class selector (.hidelem), but doesn't when I use something a bit more complicated (for example, $("*:not(.sidemenu)").toggleClass("hidden"); or $("*").not(".sidemenu").toggleClass("hidden");); these just lead to a blank window.
Could you tell me what I'm missing here?
JSFiddle: https://jsfiddle.net/et978wjw/5/ (full functionality is missing but I hope you get the idea)
The problem is that you may be skipping .sideMenu with $("body *:not(.sidemenu)"), but you are not skipping its parent DIV. If you hide an ancestor, you hide all its descendants too. You also do not skip any descendants, so the children of .sidemenu are also hidden
So you need to exclude anything that is an ancestor of .sidemenu with :not:(has()), then exclude the sidemenu itself, then exclude any children of sidemenu:
$("#container :not(:has(.sidemenu)):not(.sidemenu):not('.sidemenu *')").toggleClass("hidden");
JSFiddle: https://jsfiddle.net/TrueBlueAussie/et978wjw/8/
You really should direct the hide/show at something more specific though. Perhaps a wrapper div around everything you want hidden? I added one for the demo.
Now having said all that, your selection process is quite complicated. You would be better off simply adding a class to all the things you want to toggle instead and just toggle those (you already have nodisplay on the divs, so I used that for now).
e.g. just this:
$(".nodisplay").toggleClass("hidden");
JSFiddle: https://jsfiddle.net/TrueBlueAussie/et978wjw/9/

Select a div insinde another div with jQuery

So I try to select a div within another div. My html goes like this:
<div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div>
I want to select my #cube0 within my Stage_game_page specifically, with jQuery or JS.
The goal of the selection is to use it in an loop.
I tried :
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#Stage_game_page")$("#cube"+i)[...]
}
I don't understand what I'm doing wrong.
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#cube"+i);
}
This is sufficient to select the "#cube0"/"#cube1"/"#cube2" etc. especially since ids are always unique. To answer the question $("#cube0", "#Stage_game_page")... that is how you select a div in another div
The id attribute should only be used once! I see above that you're using id="cube0" twice. If you want your divs to be recognized in multiple instances, use a class instead (the . instead of the #). Using the same id twice will probably break your script.
I believe for your html, you could use id "cube0", "cube1", etc., as long as you're ok with entering them manually. That should work for the loop you'd like to use.
Loops through each div that starts with the id cube inside Stage_game_page1
$("#Stage_game_page1 > div[id^='cube']").each(function () {
alert($(this).html());
});
JSFiddle
Child Selctor
Starts with Selector
use each() for loop.
$('#Stage_game_page1').children().each(function(index) {
// your code here with index starts from 0
});
or this using jquery attribute starts with selector
$('#Stage_game_page1').find('[id^="cube"]').each(function(index) {
// your code here
});
You need to use .find() or .children() or the like.
The correct jQuery usage would be
$("#Stage_game_page").find('#cube'+i)
to find a div with that id inside the container #stage_game_page
You have duplicate cube0 in your html code..
and i think the look should contain something like that:
$("#cube"+i)[...]
One another solution is:
$("#Stage_game_page1 div[id='cube0']")

jQuery click function using same classes

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.

jQuery ways to dynamically .append a div to the dom, and then find it later without setting an ID, class, or anyway to indentify it

Update: Everyone that contributed, it's well appreciated, you all are very kind and generous and all of you deserve my dear respect. Cheers.
Note: I'm making a simple jQuery tooltip plugin, the tooltip will fire on mouseover. The mouseover will create an instance of the div tool-tip that will be specific to each anchor that launched the div tool-tip. So each anchor with the class .c_tool will have its own created div that will erase after mouseout. Anyway all those details are irrelevant. What is important is how to create a div with .append() or .add() on and then find a way to call it and apply actions to that div without setting an identifier (id), class, or any means to identify it.
I know theres a way you could find the div by counting, so if you gave every created div the same class and then counted them to find that one, however I don't know if this is the most efficient method that is why I'm asking for help.
I'm not going to post the whole plugin script thats unnecessary, so I'll paste a simplified version.
hover me
hover me
$(document).ready(function() {
obj = $('a.c_tool');
obj.mouseover(function() {
/// append div to body it will be specific to each item with class c_tool, however I don't want to set an ID, or CLASS to the appended div
}).mouseout(function() {
/// remove added div without setting ID or class to it.
});
});
Working example:
http://jsfiddle.net/xzL6F/
$(document).ready(function() {
var tooltip;
obj = $('a.c_tool');
obj.mouseover(function() {
var element = $('<div>', {
html: "I'm a tooltip"
});
tooltip = element.appendTo($("body"));
/// append div to body it will be specific to each item with class c_tool, however I don't want to set an ID, or CLASS to the appended div
}).mouseout(function() {
tooltip.remove();
/// remove added div without setting ID or class to it.
});
});
To create a new DOM node you can use the jQuery constructor, like
$(document).ready(function() {
obj = $('a.c_tool');
obj.mouseover(function() {
if(!$.data(this, 'ref')) {
$.data(this, 'ref', $ref = $('<div>', {
html: 'Hello World!'
}).appendTo(document.body));
}
}).mouseout(function() {
$.data(this, 'ref').remove();
});
});
.appendTo() returns the DOM node of invocation (in this case, the newly created DIV) as jQuery object. That way you can store the reference in a variable for instance and access it later.
Referring your comment:
To remove all stored references, you should do this:
$('a.c_tool').each(function(index, node) {
$.removeData(node, 'ref');
});
you can use $.append(
);
http://api.jquery.com/append/
and to find the DOM created dynamically u can use
$("#dynamicallyCreatedDOMid").live("yourCustomTrigger",function(){
});
http://api.jquery.com/live/

jQuery removeClass except on current id

[ Live Demo ]
I have a navigation menu that displays a certain state when hovered and also displays text in a different div.
In the event that the user does not interact with the menu, the divs auto cycle on their own and the navigation menu displays the corresponding hover state as if the user were interacting.
However, as it is cycling, if the user hovers over another link on the navigation menu, I need to removeClass on the previously highlighted element.
How do I write, "if id is not currently hovered id, then removeClass('hoverBold') on all other navigation links"
Look at jQuery not().
Something like...
$('.myMenu').hover(function() {
$('.myMenu').not(this).removeClass('hoverBold');
});
Just add this to hoverIn:
links.removeClass('hoverBold');
You don't need to take the class off the other elements, because the current element, a:hover.sliderLinks, shares styling with hoverBold
Working example: http://www.jsfiddle.net/MXSkj/1/
Something like this?...
$('#nav li').mouseover(function(){
//remove from others
$('#nav li').removeClass('hoverBold');
//add to this
$(this).addClass('hoverBold')
});
one way to do this would be to remove the hoverBold class on all links and add the it on the current link.
$(".sliderLinks").hover(function(){
$(".sliderLinks").removeClass("hoverBold");
$(this).addClass("hoverBold");
},function(){
//..resume the automatic behaviour
});
Other would be to use the .is() method inside the function passed to $(".sliderLinks").each() to see if its current element
Look at .filter
$(".myMenu").click(function() {
// store current object
var that = this;
$(".myMenu").filter(function() {
// check object in list is not current object
return this != that;
}).removeClass("hoverBold");
});
Basically you pass a filtering function and every object is tested. If the filter returns false (i.e. this == that) then the object is removed from the list.

Categories

Resources