Using next() x number of times with jQuery - javascript

What's an easy way to iterate x number of times using next() (applying the same function each time)?
I am working in Sharepoint and have limited control of the HTML; what I can do is find an element by its ID, track down the closest <td>, hide() it, and then move on to the next one (I don't want all the <td>'s, just about 7 or 8 in a row).
The code below works but it's not that pretty.
$("#my-easily-identifiable-id").closest("td").hide();
$("#my-easily-identifiable-id").closest("td").next().hide();
$("#my-easily-identifiable-id").closest("td").next().next().hide();
$("#my-easily-identifiable-id").closest("td").next().next().next().hide();
[ ... etc ... ]
What's a better way to do this?
Thanks
PS: added a fiddle (genius)

Use .nextAll() + .andSelf() with .slice().
$("#my-easily-identifiable-id").closest("td").nextAll().andSelf().slice(0, 7);

I think a simpler solution than those posted so far would be .nextUntil():
//to get next 8 elements
var i = $('#my-easily-identifiable-id').index();
$('#my-easily-identifiable-id').closest('td').nextUntil('', ':lt(' + (i+8) + ')');
//to get self and next 3
var i = $('#my-easily-identifiable-id').index();
$('#my-easily-identifiable-id').closest('td').nextUntil('', ':lt(' + (i+3) + ')').andSelf();
Grabs all "next" elements until the filter is hit (in this case we choose the next 8 elements). Verified by jsFiddle.

I've not tried it, but perhaps the following might work (I'll test momentarily):
$("#my-easily-identifiable-id").siblings().slice($(this).index(),($(this).index() + 8)).hide();
Tested and verified with a JS Fiddle demo.

Maybe something like this:
$("#my-easily-identifiable-id").closest("td").hide();
$("#my-easily-identifiable-id").closest("td").nextAll().hide();

Related

forEach loop, stacks classes

I have a hmtl template which replicates with a forEach loop. And I use .length of the template to give the new divs class names that are unique.
The problem is that it the newest template has all the previous classes.
"residentRetainRequest check jqbr_active residentRetainRequest-0 residentRetainRequest-1 residentRetainRequest-2 residentRetainRequest-3"
How do I get rid of the previous classes and only keep the latest? So the result above is "residentRetainRequest check jqbr_active residentRetainRequest-3" instead.
Parts of the code
The reason behind:
temp.find('.residentRetainRequest').attr 'data-key', 'residentRetainRequest-' + iCnt
Is that i use another function, and use this to call it.
The problem seems to be this line of code which is always selecting all items with class residentRetainRequest:
temp.find('.residentRetainRequest').addClass("residentRetainRequest-" + iCnt);
Instead this code will select only the last item to add residentRetainRequest with current count i:
temp.find('.residentRetainRequest').last().addClass("residentRetainRequest-" + iCnt)
The solution was using .removeClass as mention.
temp.find('.residentRetainRequest').addClass("residentRetainRequest-" + iCnt)
temp.find('.residentRetainRequest').removeClass('residentRetainRequest-' + (iCnt - 1))
Therefore i will get rid of the previous classes and only have the last one remaning.

How to condense similar duplicate jquery functions

Well if my maths is right, my Jquery file is 16 times bigger than it could be.
I am building a tabbed category page which looks like this..
Tab1
cat1
cat2
etc
Tab2
cat1
cat2
etc
All content starts of hidden and then appears when a button in the category header is clicked (also toggling an arrow up/down).
$("#tabName_contentLink_cat1").click(function(){
$("#tabName_contentLink_cat1 > .arrow").toggleClass('greyArrow_down')
.toggleClass('blackArrow_up');
$("#tabName_content_cat1").slideToggle("fast");
});
This code works fine but I've repeated it 16 times!
The only part that varies is the number at the end of '_cat1'.
How can I convert this one piece of code, so that it can be reused 16 times?
I am a newbie, so please keep that in mind.
In my mind; assigning some sought of unique identifier (applicable category number), collecting it in a jQuery variable onClick and then pasted at the end of each _cat'HERE' seams like the way forward. I haven't a clue on how to carry it out though.
Thanks
you could add another class to all cat elements and then use it as selector or you can do what i did. Notice i made the code smaller, efficient. And it does what you wanted by using Function.
addClick(cat1);
addClick(cat2);
addClick(cat3);
addClick(cat4);
function addClick(x) {
$("#tabName_contentLink_"+x).click(function(){
$(this).slideToggle("fast").children(".arrow")
.toggleClass('greyArrow_down blackArrow_up');
});}
What about
$("[id^='tabName_contentLink_cat']").click(function(){
$(this).children(".arrow").toggleClass('greyArrow_down')
.toggleClass('blackArrow_up');
var contentId = this.id.replace(/contentLink/, 'content');
$("#"+ contentId).slideToggle("fast");
});
It's not the most elegant code, but it should work.
Why don't you use a simple for loop?
for(var i = 1; i <= 16; i++){
$("#tabName_contentLink_cat" + i).click(function(){
$("#tabName_contentLink_cat" + i + " > .arrow").toggleClass('greyArrow_down')
.toggleClass('blackArrow_up');
$("#tabName_content_cat" + 1).slideToggle("fast");
});
}
There are other options, but this seems to be the quickest way to make it work without changing too much of the existing code. To make it more generic you can wrap it in a function that receives 'i' as an argument.
Give them all the tabName_contentLink class, then:
$(".tabName_contentLink").click(function(){
$(this).children(".arrow").toggleClass('greyArrow_down')
.toggleClass('blackArrow_up');
$(this).find(".tabName_content").slideToggle("fast");
});
The keyword this allows you to reference the object calling the function, thus relate to a specific object out of a set. It can become a little tricky, but basically - you can use it as described above.

Use a Selector instead of "this" in Jquery

Maybe it's a silly question. But I really can't understand it.
I'm using the Jquery Cycle2. And after some personalization I got a simple problem.
I need to know what is the "Index" of my current slide.
On the plugin's website a found this line of code that perfectly works.
$('#cycle-1 .cycle-slide').click(function(){
var index = $('#cycle-1').data('cycle.API').getSlideIndex(this);
alert(index);
});
It gives me the right index. But I'm trying to catch this Index when another element is clicked. So I can't use the parameter (this).
Then I tried this.
$('.anotherelement').click(function(){
var mycycle = $('#cycle-1 .cycle-slide');
var index = $('#cycle-1').data('cycle.API').getSlideIndex($(mycycle));
alert(index);
});
It doesn't return my current slide index. It returns "-1". Does anyone knows how I should pass the Object (selector) as a parameter to the getSlideIndex() ?
Thanks a lot :D
You can use $('.cycle-slideshow').data('cycle.opts').currSlide to get the current slide index
$('.anotherelement').click(function(){
var index = $('.cycle-slideshow').data('cycle.opts').currSlide;
var currSliderNum = index+1;
alert(currSliderNum);
return false;
});
FIDDLE
In the first piece of code this is a DOM element and not a jquery object. Try this instead:
var index = $('#cycle-1').data('cycle.API').getSlideIndex(mycycle[0]);
However, presumably, you have multiple .cycle-slide elements. This will just get the first one. In your first code you have access to a single one since only one was clicked. You need to decide which one you want to target here.

Easy level, selecting elements in DOM, optimization, creating method function

Please, do not laugh, too much. I know jQuery ans JS for a short a while.
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
For the first one, why do you need a selector like that? couldn't you find something less specific to hook onto? If you must keep it when joining an number and a string, JavaScript will convert the number to string behind the scenes so you don't really need the .toString() and could do the "maths" +/-1 outside of your selector making it more readable.
Edit
In regards to your comment I am not really sure what you mean, you could assign a class to the "post" items and then add the unique id to a data-attribute ID. To make it simpler you could do something like this:
var codeLt = aktywneZdanie + 1,
codeGt = aktywneZdanie - 1;
$('code:lt(' + codeLt + '):gt(' + codeGt +')').removeClass('class2');
End Edit
And the second solution should work, all your doing is passing the dom elements found from your selector into a function as a jQuery "array" in which manipulate to your needs
And for your second question why not just toggle the class on and off? having a default state which reflects class one?
jQuery('#something').toggleClass('uberClass');
Or you can pass your selector to the function
changeClasses(jQuery('#something'));
Then inside you function work on the return elements.
Edit
Your code should work fine, but id suggest checking to make sure you have got and element to work on:
changeClasses(jQuery('#something'));
function changeClasses($element){
if($element.length > 0) {
$element.addClass('class1');
}
}
End Edit
Hope it helps,
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
I stoped creating this wierd code like this one above, instead I start using .slice() (do not forget to use .index() for arguments here), .prev(), .next(). Just those three and everything is faster and clearer. Just an example of it below. No it does not do anything logical.
var activeElem = jQuery('code:first');
var old Elem;
jQuery('code').slice('0',activeElem.index()).addClass('class1');
oldElem=activeElem;
activeElem=activeElem.next();
jQuery('code').slice(oldElem.index(),activeElem.index()).addClass('class1');
oldElem.toggleClass('class1');
activeElem.prev().toggleClass('class1');
and the second part
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
This one is still unsolved by me.

Javascript taking too long to run

I have a script that is taking too long to run and that is causing me This error on ie : a script on this page is causing internet explorer to run slowly.
I have read other threads concerning this error and have learned that there is a way to by pass it by putting a time out after a certain number of iterations.
Can u help me apply a time out on the following function please ?
Basically each time i find a hidden imput of type submit or radio i want to remove and i have a lot of them . Please do not question why do i have a lots of hidden imputs. I did it bc i needed it just help me put a time out please so i wont have the JS error. Thank you
$('input:hidden').each(function(){
var name = $(this).attr('name');
if($("[name='"+name+"']").length >1){
if($(this).attr('type')!=='radio' && $(this).attr('type')!=='submit'){
$(this).remove();
}
}
});
One of the exemples i found : Bypassing IE's long-running script warning using setTimeout
You may want to add input to your jquery selector to filter out only input tags.
if($("input[name='"+name+"']").length >1){
Here's the same code optimised a bit without (yet) using setTimeout():
var $hidden = $('input:hidden'),
el;
for (var i = 0; i < $hidden.length; i++) {
el = $hidden[i];
if(el.type!=='radio' && el.type!=='submit'
&& $("[name='" + el.name + "']").length >1) {
$(el).remove();
}
}
Notice that now there is a maximum of three function calls per iteration, whereas the original code had up to ten function calls per iteration. There's no need for, say, $(this).attr('type') (two function calls) when you can just say this.type (no function calls).
Also, the .remove() only happens if three conditions are true, the two type tests and check for other elements of the same name. Do the type tests first, because they're quick, and only bother doing the slow check for other elements if the type part passes. (JS's && doesn't evaluate the right-hand operand if the left-hand one is falsy.)
Or with setTimeout():
var $hidden = $('input:hidden'),
i = 0,
el;
function doNext() {
if (i < $hidden.length) {
el = $hidden[i];
if(el.type!=='radio' && el.type!=='submit'
&& $("[name='" + el.name + "']").length >1) {
$(el).remove();
}
i++;
setTimeout(doNext, 0);
}
}
doNext();
You could improve either version by changing $("[name='" + el.name + "']") to specify a specific element type, e.g., if you are only doing inputs use $("input[name='" + el.name + "']"). Also you could limit by some container, e.g., if those inputs are all in a form or something.
It looks like the example you cited is exactly what you need. I think if you take your code and replace the while loop in the example (keep the if statement for checking the batch size), you're basically done. You just need the jQuery version of breaking out of a loop.
To risk stating the obvious; traversing through the DOM looking for matches to these CSS selectors is what's making your code slow. You can cut down the amount of work it's doing with a few simple tricks:
Are these fields inside a specific element? If so you can narrow the search by including that element in the selector.
e.g:
$('#container input:hidden').each(function(){
...
You can also narrow the number of fields that are checked for the name attribute
e.g:
if($("#container input[name='"+name+"']").length >1){
I'm also unclear why you're searching again with $("[name='"+name+"']").length >1once you've found the hidden element. You didn't explain that requirement. If you don't need that then you'll speed this up hugely by taking it out.
$('#container input:hidden').each(function(){
var name = $(this).attr('name');
if($(this).attr('type')!=='radio' && $(this).attr('type')!=='submit'){
$(this).remove();
}
});
If you do need it, and I'd be curious to know why, but the best approach might be to restructure the code so that it only checks the number of inputs for a given name once, and removes them all in one go.
Try this:
$("[type=hidden]").remove(); // at the place of each loop
It will take a short time to delete all hidden fields.
I hope it will help.
JSFiddle example

Categories