Looping fade between two divs - require modification to answer to this post - javascript

The accepted answer to this stackoverflow question is exactly what I need, but with one modification.
I need multiple .boxes. Not just one.
Each "box" has two divs that need to be faded between.
From this snippet of the code:
$(document).ready(function () {
var allBoxes = $("span.boxes").children("span");
transitionBox(null, allBoxes.first());
});
I understand that I should maybe first, put all the .boxes into an array and then loop over that to get each of their children span elements.
But I'm not entirely sure that this is (a) the best practice, (b) correct, and (c) if there is just a better way in the first place.

Do you mean something like this http://jsfiddle.net/8odoros/CYJLA/306/ ?
Using
$( "div.boxes" ).each(function( index ) {
var allBoxes = $(this).children("div");
transitionBox(null, allBoxes.first());
});
applies the same effect to all .boxes

Related

How to select some elements and append a div after them?

I've bene bursting my head for the last few hours. Here's the situation:
I have a website that has many divs, but many of them share classes (they are equal) but have some different texts. Example:
<div class="summary-title">
I Am That Girl</div>
<div class="summary-title">
I Am That Girl</div>
What I want to do is select each one of these divs and add a span whenever another div is hovered.
I mean, this is what I want to do: hover a div that's before the sumary-title div, a span with a class is appended inside the sumary-title div or out of it, whatever works.
That's what I got so far:
$('summary-title').each(function(index) {
var content = $(index).next().text();
$(index).append("<span class='hover-text'>"+content+"</span>");
});
But I get an error that $ is not defined, probably because it is a closure?
I have no idea what to do. The code seems horrible too — i need to do this quickly and I just can't do. Would anyone help me at least know what to do?
Thanks
append() is already an implicit iteration ( that loops through the set of elements in the jQuery collection.) and it's unnecessary to call .each() .
$('.summary-title').append(function() {
return "<span class='hover-text'>" + $('a', this).text() + "</span>";
});
Outside of making sure you have jQuery on your page and properly referring it, your code should go like:
$('.summary-title').each(function() {
var content = $(this).children('a:first').text();
$(this).append("<span class='hover-text'>"+content+"</span>");
});
Notice:
dot in class selector - $('.summary-title')
this instead of index - $(this)
children selector instead of next
Check demo - Fiddle.
To append this to a preceding element on hover use:
$(document).ready( function() {
$('.summary-title').hover( function() {
var content = $(this).children('a:first').text();
$(this).prev().append("<span class='hover-text'>"+content+"</span>");
});
});

Jquery : Hide all children, and their children and etc... of a tag

I'm making a game in DOM (javascript + jquery) and I need to switch stages, for that I need to hide all from one stage, and show all of a new one. The showing part is easy cuz I'm creating new stuff. But I'd like a clean way of finding every last single child of a div, all his descendance, cousin, niece I don't care, and hide them. To show that in code something like :
while (child = $(this).hasChildren)
{
child.hide();
}
Instead of something like that :
$(this.id).children().children().children().hide();
$(this.id).children().children().hide();
$(this.id).children().hide()
$(this.id).hide();
The goal is to hide his children, and his children's children, and so on.
I hope I'm not too confusing.
Thanks in advance for the answers!
EDIT: for someone that doesn't want to hide the children, but access them all, and you can't use .find("*") then answer number two might be more adapted for you (the one from Rajan Goswami).
If you want to perform something on all children of an element you can use this syntax:
$('#myDiv *').hide();
or using .find()
$('#myDiv').find('*').hide();
Of course you can use any function, not just .hide()
You can try the following solution:
"myParentControl" is the ID of the parent-most control.
$(document).ready(function(){
HideChildren($(#myParentControl))
})
function HideChildren(cntrl){
if ( $(cntrl).children().length > 0 ) {
$(cntrl).children().each(function(){
HideChildren(this);
$(this).hide();
})
}
}

How do I cycle through a group of jQuery elements - 4 at a time?

I'm a little confused. Basically, I've got 16 span elements on my page which are displaying brands. I want to show only 4 brands at a time, and then set an interval to show the next 4 brands until I reach the end, at which point I'll reset a counter and start from the beginning again. Here is what I was thinking:
Display all brand span elements
Put all of the brand elements into an array
Count first 4 items (brands) and give them the class of visible
After 5 seconds, hide all elements with class of visible
Display the next 4 items in the array
When the end of the array is reached, reset the counter and start again
Some general advice or help with jquery arrays would be appreciated. I'm looking for the most dynamic and simple solution possible.
Thanks :)
Here, it's a bit hackish though...
var elems = $( 'span' ).hide().get();
(function loop () {
var i = 0, pointer;
pointer = $( elems ).filter( ':visible:last' )[0] || $( elems ).last()[0];
$( elems ).hide();
while ( i < 4 ) {
pointer = $( pointer ).next()[0] || $( elems ).first()[0];
$( pointer ).show();
i += 1;
}
setTimeout( loop, 5000 );
})();
Live demo: http://jsfiddle.net/hBrt6/
If you require an explanation of the code, just let me know...
A few explanations:
.get() returns an array of the DOM elements inside the jQuery object.
So
$( 'div' ).get()
gives you an array of all the DIV elements on the page.
Using the property accessor operator [i] will give you the i-th DOM element from the jQuery object.
So
$( 'div' )[4]
returns the fifth DIV element on the page.
It is important to understand that you cannot invoke jQuery objects on DOM elements itself (or arrays of DOM elements).
So this
$( 'div' )[4].hide();
throws an error. DOM elements don't have a hide method.
If you want to target a specific element inside a jQuery object and while still retaining a jQuery object, use .eq().
This
$( 'div' ).eq( 4 ).hide();
works just fine.
Now that you understand this difference, let me explain why I use get() and [i] in my code: The thing is, I don't like to store jQuery objects inside variables. Instead I prefer to work with DOM elements and arrays of DOM elements directly.
When I need to invoke a jQuery method on some element or array of elements, I just wrap it inside the $() function first.
So this
$( elems ).hide();
works just fine.
And when the jQuery method has done the job, I just append .get() or [0] to "unwrap" the jQuery object = to get my element(s) back.
If the data exist as a JavaScript object then you can use JQuery templates to render the HTML.
You would do the following
Get all data in array of JavaScript objects (might already have this)
Empty the target element container you are inserting too ($('#target').empty())
Slice the array to only have the 4 elements you want (data.slice(index, index+4))
Render template into target element container with sliced array as the model ($('#template').tmpl(slicedArray).appendTo('#target'))
You should be able to do step 3 with a for loop that steps by 4. And in the template use the {{each}} method to loop over the row creation.
Ok, my solution will be as dynamic and simple as I will think to be possible. I'm good at making things like that and am quite good at jQuery and JavaScript so I thought I'd try my hand at this. I'll just write the best code I can think of here and show where you need to edit your other code after.
$("#ContainerElement.span:gt(4)").hide();
var i = 0;
var b = setInterval("BrandChange();",5000);
function BrandChange()
{
$("#ContainerElement.span:eq(i),
#ContainerElement.span:eq(i+1),
#ContainerElement.span:eq(i+2),
#ContainerElement.span:eq(i+3)").hide(normal,function(){
i+=4;
if(i == 16) i = 0;
$("#ContainerElement.span:eq(i),
#ContainerElement.span:eq(i+1),
#ContainerElement.span:eq(i+2),
#ContainerElement.span:eq(i+3)").show(normal);
});
}
I had to look up some jQuery selectors to figure this out, but that doesn't disprove it's validity, basically it first hides all the span elements in the Element which holds them, which will need an id of "ContainerElement" starts an interval for the BrandChange function, which fades out and hides the four current brands, then fades in and shows the next four brands, while incrementing the i variable to keep count, then it waits for the interval to happen again in five seconds. It's not necessarily the way you planned to do it, but I think you'll find it does exactly what you want it to. If you have any questions, just ask. :)

Remove all classes except one

Well, I know that with some jQuery actions, we can add a lot of classes to a particular div:
<div class="cleanstate"></div>
Let's say that with some clicks and other things, the div gets a lot of classes
<div class="cleanstate bgred paddingleft allcaptions ..."></div>
So, how I can remove all the classes except one? The only idea I have come up is with this:
$('#container div.cleanstate').removeClass().addClass('cleanstate');
While removeClass() kills all the classes, the div get screwed up, but adding just after that addClass('cleanstate') it goes back to normal. The other solution is to put an ID attribute with the base CSS properties so they don't get deleted, what also improves performance, but i just want to know another solution to get rid of all except ".cleanstate"
I'm asking this because, in the real script, the div suffers various changes of classes.
Instead of doing it in 2 steps, you could just reset the entire value at once with attr by overwriting all of the class values with the class you want:
jQuery('#container div.cleanstate').attr('class', 'cleanstate');
Sample: http://jsfiddle.net/jtmKK/1/
Use attr to directly set the class attribute to the specific value you want:
$('#container div.cleanstate').attr('class','cleanstate');
With plain old JavaScript, not JQuery:
document.getElementById("container").className = "cleanstate";
Sometimes you need to keep some of the classes due to CSS animation, because as soon as you remove all classes, animation may not work. Instead, you can keep some classes and remove the rest like this:
$('#container div.cleanstate').removeClass('removethis removethat').addClass('cleanstate');
regarding to robs answer and for and for the sake of completeness you can also use querySelector with vanilla
document.querySelector('#container div.cleanstate').className = "cleanstate";
What if if you want to keep one or more than one classes and want classes except these. These solution would not work where you don't want to remove all classes add that perticular class again.
Using attr and removeClass() resets all classes in first instance and then attach that perticular class again. If you using some animation on classes which are being reset again, it will fail.
If you want to simply remove all classes except some class then this is for you.
My solution is for: removeAllExceptThese
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
$.fn.removeClassesExceptThese = function(classList) {
/* pass mutliple class name in array like ["first", "second"] */
var $elem = $(this);
if($elem.length > 0) {
var existingClassList = $elem.attr("class").split(' ');
var classListToRemove = existingClassList.diff(classList);
$elem
.removeClass(classListToRemove.join(" "))
.addClass(classList.join(" "));
}
return $elem;
};
This will not reset all classes, it will remove only necessary.
I needed it in my project where I needed to remove only not matching classes.
You can use it $(".third").removeClassesExceptThese(["first", "second"]);

jquery select multiple <p> in <div>

HTML:
<div id='example'>
<p> First paragraph</p>
<p> Second paragraph</p>
<p> Third paragraph</p>
</div>
Javascript with JQuery:
var paragraphs = $('div#examples p');
This returns an array of HTMLParagraphElement objects. However, I wish to return Jquery objects. (So that I can use e.g:
for(i=0;i<paragraphs.length;i++)
{
paragraph[i].hide();
}
Is there a way I can easily do this? Thanks.
example:
$('#examples p').hide();
div is not necessary
This the the most performant way to query the dom for present issue:
$('#examples).find('p').hide();
It's a few more keystrokes, but the selection happens so much faster than the examples given here by others. The reason being is that it traverses all divs first, then finds those that may have the given id, then traverses to find their matching p tags.
In my solution it finds just #examples and then traverses down to its p tag.
You can still use the the selector query you use. i.e:
var paragraphs = $('div#examples p');
paragraphs.hide();
or
$('div#examples p').hide();
Thanks everybody for input. Iteration of the div p array was necessary (sorry if that wasn't clear), so doing $('div#example p').hide(); was not a proper solution. I ended up doing the following:
var arr = $('div#example p');
for(i=0;i<arr.length;i++)
{
$(arr[i]).hide();
}
Hope this is useful for people in the future:)
try this...
$('div#examples p').hide();
From the looks of your question the answer would be, as stated by others:
$('div#examples p').hide();
But for the case that you have to iterate through each object that is returned from a jQuery query you should use this syntax:
$('div#examples p').each(function(){
$(this).hide();
});
But remember, if it's as simple as hide, then just use the first example. The second example is when the applied function is specific to each object. The next example is doubling the heights of all returned objects, which could not be done in the same way that the first example is:
$('div#examples p').each(function(){
var h = $(this).height();
$(this).height(h * 2);
});

Categories