target single element when it is not possible to use $(this) - javascript

function modalClosed(){
$("div#tab" + tabId).find('ul')
.prepend("<li>item</li>")
.hide()
.fadeIn('slow');
}
I want the list (<li>) to be prepended and have fade in effect one by one, unfortunately I have no way of using $(this), the above code doesn't work well, it apply effect on all of the <li>.

That's because .prepend() returns the ul element not the appended li element, so you are hiding/showing the ul element. You can reverse the logic using prependTo() method, now .hide() and .fadeIn() are applied to the appended element not the ul element.
$("<li>item</li>").hide()
.prependTo("#tab"+tabId+" ul")
.fadeIn('slow');
http://jsfiddle.net/5yj7v/

function modalClosed(num) {
$("div#tab" + tabId).find('ul')
.prepend("<li>item</li>")
.hide()
.fadeIn('slow', function() {
// callback function, called when fadeIn has finished
if(num > 1) {
modalClosed(num - 1);
}
});
}

From what I understand You want fade in effect one by one on all li items. If that is correct then try the following:
var time=1000;
$("div#tab"+tabId+" ul").prepend("<li>item</li>");
$("div#tab"+tabId+" ul li").each(function() {
$(this).hide();
$(this).fadeIn(time);
time+= 800;
});
http://jsfiddle.net/PV4dC/5/

Related

Animate siblings one by one with delay

Im trying to create animation function where I click on lets say the last child in a list,
then I'll need to move all siblings one by one to the left. So it will go like a wave.
Example:
Click on child nr.4, sibling nr.1 starts to move to the left out of the screen, and with a short delay sibling nr.2 and so on follow after. So it will be like a wave effect.
I have created a JSFiddle: http://jsfiddle.net/10kjn00z/2/
$('#menu li').click(function(){
setVar(this);
$(this).siblings().animate({left: '-'+tWidth+'px'}, function() {
$(this).animate({top: '-'+onSet+'px'});
});
});
This fiddle is just a short snippet off my code, so there might be code thats isnt in use here. But I'll get the idea.
Thanks
You can use the setTimeout() function to achieve what you want.
Here's an example of how you can do it:
$('#menu li').click(function(){
var speed = 100;
setVar(this);
var siblings = $(this).siblings();
$.each( siblings, function(index,value){
setTimeout(function(){$(value).animate({left: '-'+tWidth+'px'});}, index*speed);
});
var current = this;
setTimeout(function(){$(current).animate({top: '-'+onSet+'px'})}, 400-speed+siblings.length*speed);
});
Check it out on jsFiddle
if all the elements to be shifted belong to the same parent:
$('menu li').click(function(event) {
var list = event.currentTarget.parentNode.children;
var i = list.length;
var timeout = 100
while (i--) {
setTimeout(function() {
$(list[i]).animate(/*logic here*/);
}, timeout);
timeout += 100;
}
})
This will iterate through all the children of the parent in reverse order and apply the animation. You can also tweak this to only call on certain siblings. If you want them to iterate in order, use the standard for loop instead of while. The value timeout corresponds to milliseconds of delay and you can adjust the initial and increment values to adjust the animation timing.
You can achieve that behaviour using jQuery.fn.delay, where the delay-time depends on the elements position in the siblings-list.
$('#menu li').click(function(){
setVar(this);
// call .each on siblings, because each will get a different delay
$(this).siblings().each(function(index, sibl) {
$(sibl).delay( index * 250 )
.animate({left: '-'+tWidth+'px'}, function() {
$(this).animate({top: '-'+onSet+'px'});
});
});
});

How to generate dynamic id using jQuery?

I want to add progressive id to a series of elements on an unordered HTML list. I used the jQuery .each() method to get each <li> of the List and append a <span> inside each <li>. Then I added the ID attribute with index of each() as number.
$('#menu li ul li').each(function(i, e){
$(this).append('<span class="arr"></span>');
$(".arr").attr("id", "id_" + i);
});
Fiddle Demo
But I get id_3 for all elements. Why? What did I do wrong?
Thanks for any help!
It is because you are applying it to .arr globally, so overriding it every time.
You need to be more specific with adding it, by finding the .arr in you current li.
Change your code to be:
$('#menu li ul li').each(function(i, e){
$(this).append('<span class="arr"></span>');
$(this).find(".arr").attr("id", "id_" + i);
});
As has been pointed out, $(".arr") targets every element with the arr class, so on the fourth iteration you update all such elements to the id_3 id.
You can limit the selection with $(".arr", this) or $(this).find(".arr"), but it would be easier to just turn the append around:
$('#menu li ul li').each(function(i, e){
$('<span class="arr"></span>')
.attr("id", "id_" + i)
.appendTo(this);
});
That is, create the element first, set its id, then use .appendTo() instead of .append().
Or rather than calling .attr() you can pass the desired attributes directly to the $() function when you create your span:
$('#menu li ul li').each(function(i, e){
$('<span></span>', {
"class": "arr",
"id": "id_" + i
}).appendTo(this);
});
You are targeting a class when assigning the attribute. Every element you create is created with the same class so all items get assigned the same attribute. This code saves the newly created element to a variable called elem and then sets the attribute ID of that newly created element.
var elem = $(this).append('<span class="arr"></span>');
elem.attr("id", "id_" + i);
You need to scope your $(".arr").attr("id", "id_" + i); selector. Its currently pulling all the <span> tags each time. I'm guessing you have 4 total at this point, which is why they are all getting set to "id_3".
Added in $(this) to your selector.
$('#menu li ul li').each(function(i, e){
$(this).append('<span class="arr"></span>');
$(".arr", this).attr("id", "id_" + i);
});
Modified Fiddle: http://jsfiddle.net/NZgyD/2/
you can do it this way
$('#menu li ul li').each(function(i, e){
$(this).append('<span id="id_' + i + '" class="arr"></span>');
});
because $(".arr") is selector for multiple items

Hide div if the ul is empty

Here is my html,
<div id="personaldetails">
<ul>
<li class="clear"></li>
</ul>
<ul>
<li class="clear"></li>
</ul>
</div>
I want to hide div personaldetails when all the ul inside in div is empty.
If the ul is having element <li class="clear"></li> then the ul is considered as to be empty.
How to do this using Jquery ?
You can try this:
$('#personaldetails').find('ul').each(function(){
var txt = $("li", this).text();
if(txt.length <= 0){
$(this).hide();
}
});
if(!$('#personaldetails').find('ul:visible').length){
$('#personaldetails').hide();
}
Updated Fiddle
And to me you should hide all ul, if no ul are visible then you can hide the #personaldetails div.
Even one of answer is already accepted, I think it can be simple as:
if($.trim($("#personaldetails").text()) == '') {
$("#personaldetails").hide();
}
:)
Take a look at that code:
function foo(){
var all_li_clear = true;
$("#personaldetails > ul > li").each(function(){
if(!$(this).hasClass("clear")){
all_li_clear = false;
break; // No need to continue now
}
});
if(all_li_clear){
$("#personaldetails").hide();
}
}
You can see a fiddle example there, just comment and discomment foo(); line.
Javascript solution:
This will only hide the div if all li have clear class
$(function() {
emptyLi = $('#personaldetails ul li').filter(function(){
/*if($(this).hasClass('clear')){
return true;
}else{
return false;
}*/
return $(this).hasClass('clear');
}).length;
if($('#personaldetails ul li').length == emptyLi){
$('#personaldetails').css('display','none');
}
});
CSS:
This will hide the li with class clear, so if you not fixed height of ul or li and don't have padding , margin given to ul,li your div personaldetails will get hidden automatically when all li element have class clear
#personaldetails ul li.clear{
display:none;
}
-UPDATED-
You can use following code if you are deciding empty class based on clear class.
if($("#personaldetails ul li:not(.clear)").length == 0) {
$("#personaldetails").hide();
}
Or if you are looking for the empty div then you can just use the shortest code given by #Samiul Amin Shanto Like:
if($.trim($("#personaldetails").text()) == '') {
$("#personaldetails").hide();
}
Explanations
Method1:
$("#personaldetails ul li:not(.clear)")
This code find all li without the clear class. Then if no such li found, just hide the div. Fiddle
Method2:
$("#personaldetails").text() this code return innerHTML text striping all html tags. So no meter what the div contain ul, li or anything else, this will return the plain text content of the div, then striping any white space we can determine if the div is empty. If your intention is to hide the empty div not hiding the div which contain empty Ul this should be your choice.
This asumes that if you have the same amount of li's with the class clear, as there are ul's, they're all empty
var $wrapper = $('#personaldetails');
if( $wrapper.find('ul').length=== $wrapper.find('li.clear').length){
$wrapper .hide();
}
Everybody's fiddling examples :)
$(function($) {
$cnt = 0;
$('.personalDetails ul li').each(function() {
if($(this).hasClass('clear')) $cnt++;
});
if($('.personalDetails ul li').length == $cnt) $('.personalDetails').hide();
});
$("ul li:empty").closest('div#personaldetails').hide();
Sample Code
#personaldetails ul li.clear{
visibility:hidden;
}

How to toggle two images when clicking on the parent element?

I need to toggle two images by clicking on the parent a tag.
here is my JavaScript
$("#VerColMenu > li > a").click(function() {
var src = ($(this).children()[0].attr('src') === 'img/plus.png')
? 'img/minus.png'
: 'img/plus.png';
$(this).children()[0].attr('src', src);
});
but nothing happens here.
Attaching [0] to a jQuery object retrieves the under-lying DOM object. Along with the above/below answers, you can also use .first() to get the first element in a jQuery array set:
$("#VerColMenu > li > a").click(function() {
var src = ($(this).children().first().attr('src') === 'img/plus.png') ? 'img/minus.png' : 'img/plus.png';
$(this).children().first().attr('src', src);
});
DEMO
This of course does have to be wrapped in $(document).ready() or something similar.
attr is a jQuery method not a DOM method so you don't need [0]. Try this:
$('#VerColMenu a').click(function(){
var $img = $(this).children();
var src = $img.attr('src');
$img.attr('src', src === 'img/plus.png' ? 'img/minus.png' : 'img/plus.png');
});
Firstly .children()[0]
gets the children as the DOM object and not a jQuery Object..
And .attr() can be used only on jQuery objects..
Try the :eq selector instead of .children()
$("#VerColMenu > li > a").click(function() {
var src = ($(this).find('img:eq(0)').attr('src') === 'img/plus.png')
? 'img/minus.png'
: 'img/plus.png';
$(this).find('img:eq(0)') .attr('src', src);
});
I am assuming by .children()[0] you meant the first image inside the li ,
so using img:eq(0) which will select the first image element inside the li..
use this code it can help u
function toggle(a) {
if (isloaded) {
document.getElementById(a).src=toggleimage[i_image];
}
i_image++
if (i_image>1) {i_image=0}
}
<img name="togglepicture" src="p1.gif" border="0">

make parent menu item bold when visiting child page

I have the following code which gives the menu item a class of 'current'. I then style that with font-weight:Bold;
$(document).ready(function () {
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
}
});
});
If the user is on a page which is within the sub menu ul li a how do i add a class called Bold to the parent UL/LI at the root level?
here is the structure, if i am on Q&Z Group then About us needs to be bold. - http://jsfiddle.net/zZQy3/
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
$(this).parent('li').parent('ul').addClass("Bold");
}
});
You are looking for the parent:
$(this).parent("li").parent("li").addClass("bold");
Note there are two parents above - this is because your a element is within an li, which is not what you want bold. You want the li parent of THAT to be bold.
if you have the current node as a jquery variable, you can access its parent by using parent. So, you could use $(this).parent().addClass(...);
If you wanted to, rather than using javascript for this logic, you could use the selector:
$('ul li:has(a[href=' + window.location.href + '])').addclass(...);
This is looking for any LI that has a descendant with an href matching the current url by way of the Has and Attribute Equals selectors.

Categories

Resources