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.
Related
I am working on a javascript code where I can clone an element, but also want to delete one on click. Cloning works, but I can't remove one.
I have the following elements.
<input list="accountsdeb" name="deblist[1]" id="deblist" autocomplete="off">
<input list="accountsdeb" name="deblist[2]" id="deblist" autocomplete="off">
And now I want to remove the last one on click (last = highest number).
function remove1() {
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
var elem = document.getElementsByName("deblist["+dbla+"]");
alert(dbla);
//var last = debelelast - 1;
elem.parentNode.removeChild(elem);
}
As an orientation I used to have a look on an example from W3S and Stack. I have also seen that this works:
var elem = document.getElementById("myDiv");
elem.parentNode.removeChild(elem);
But this is random and as you can see I have tried to include this in my code.
The error I get is:
Uncaught TypeError: Cannot read property 'removeChild' of undefined
at HTMLAnchorElement.remove1 (index.php:179)
Where's the problem in my code, where is my thinking wrong?
I see two issues in the piece of code you provided,
deblist is used as id for 2 elements which is not advisable and due to this document.querySelectorAll('#deblist').length returns 2 (I am not sure if you intending to do so)
document.getElementsByName() (check here) will return a NodeList which needs to be iterated in order to access any of the returned elements. So here you need to select the child element by giving its index. In your case elem will have one element for the matched name deblist[2] and hence you need to access it like elem[0] for selecting its parent and deleting its child.
So the updated the code would be,
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
// console.log('dbla', dbla);
var elem = document.getElementsByName("deblist["+dbla+"]");
// console.log('elem 0', elem[0]);
// console.log('elem parentNode', elem[0].parentNode);
//var last = debelelast - 1;
elem[0].parentNode.removeChild(elem[0]);
Check the fiddle here
If the inputs are part of a group they could share a name property or such, and the use of jQuery could help you do something like...
$("input[name='group1']").last().parent().remove()
Or if not part of a group then just....
$("input").last().parent().remove()
hi this is my problem im currently looping all the selected element using jquery selector and tried to use .find(Selector) of jquery but i think its not working or is it possible to find an element using this code
for (var i = 0; i < $('.MainElement').find('.ItemGroup').length; i++) {
var CurrentSelectedGroup = $('.MainElement').find('.ItemGroup')[i].find('span');
}
I debugged this code and its returning a unavailable but when i tried to jquery select the element manually its working is it possible to do this??
i need to select the span inside the current element inside the loop
I have searched in google i didnt find any
Though eq() as given below works, a better approach will be is to use .each() for iteration, as you are running your selector multiple times in your script
$('.MainElement').find('.ItemGroup').each(function(){
var CurrentSelectedGroup = $(this).find('span');
})
or at the least cache the value of your selector and then reuse it in your loop
use eq()
var CurrentSelectedGroup = $('.MainElement').find('.ItemGroup').eq(i).find('span');
NOTE: $('.MainElement').find('.ItemGroup')[i] will return javascript object not jquery
Try this as it's much cleaner:
$('.MainElement').find('.ItemGroup').each(function() {
var CurrentSelectedGroup = $(this).find('span');
});
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.
This question already has answers here:
jQuery first child of "this"
(11 answers)
Closed 10 years ago.
I'm having a bit of trouble selecting the first child in jQuery. I'm trying to do this to avoid having LOTS of if statements. Basically, you click on a button. This class selector is setup to handle the click in my JS. Once you go into the JS, I want to get the child of the item that was just clicked, but I'm not having any joy.
Here's what I have in my JS:
$('.itemClicked').click(function(){
var id = $(this).attr('id').first();
// it can't find the method first() here. If I just find the id, I get the
// correct ID of what I just clicked.
var test = id.first();
// I tried the above to seperate the ID from the first() method request
// no joy with this either.
test.toggleClass("icon-tick");
// this is my ultimate aim, to toggle this icon-tick class on the item
// clicked.
});
Thanks in advance if you can help me out here. I'm probably just doing something stupid but I'm struggling to realise what that is.
Your current version doesn't work because .attr('id') just returns the ID as a string, not a jQuery object. Also, .first() returns the first item from a jQuery collection, not their children.
So, you just want:
var test = $(this).children().first();
or:
var test = $('>:first-child', this);
or:
var test = $(this).children(':first');
or (on newer browsers):
var test = $(this.firstElementChild);
In a jsperf test with Chrome 25 the .firstElementChild method was incredibly fast, but it's not available on MSIE < 9. The .children().first()was the fastest portable option, and the>:first-child' method was very, very slow.
Perhaps
$('.itemClicked').click(function(){
$(':first-child',this).toggleClass('icon-tick');
});
is what you're after.
Live example: http://jsfiddle.net/ySMLG/
If all that you want to do is toggle the class "icon-tick" on the item that was click, then this will work:
$('.itemClick').click(function () {
$(this).toggleClass('icon-tick');
});
The statement:
$(this).attr('id').first()
doesn't work because the attr() method returns the value of the attribute, not the jQuery object, so it is not chainable.
I am having issues with getting exactly values with Javascript.
Following is working version of when we have class on single item.
http://jsfiddle.net/rtnNd/
Actually when code block has more items with same class (see this: http://jsfiddle.net/rtnNd/3), it picks up only the first item which use the class name.
My issue is that I would like to pick up only the last item which use the class name. So I used following code:
var item = $('.itemAnchor')[6];
var href = $($('.hidden_elem')[1].innerHTML.replace('<!--', '').replace('-->', '')).find(item).attr('href');
But it doesn't work though. I don't really know why.
The code that may contains items are using same class, class may be use in 2 items, 3 items, or 6th times. That's why, I want to pick up only the last item to extract.
Can you explain, thank you all for reading my question.
"My issue is that I would like to pick up only the last item which use the class name."
OK, so in a general sense you would use the .last() method:
var lastItem = $('.itemAnchor').last();
Except that there are no elements in the DOM with that class because (in your fiddles) they're all commented out. This is also the reason why the code you showed in your question didn't work. The first line:
var item = $('.itemAnchor')[6];
...sets the item variable to undefined. The selector '.itemAnchor' returns no elements, so $('.itemAnchor') is an empty jQuery object and it has no element at index 6.
You need to use the '.itemAnchor' selector on the html that you get after removing the opening and closing comments with your .replace() statements, so:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor').last().attr('href');
Demo: http://jsfiddle.net/rtnNd/4/
EDIT in response to comment:
"How can we pick up the itemElement before that last one."
If you know you always want the second-last item use .slice(-2,-1) instead of .last(), as shown here: http://jsfiddle.net/rtnNd/5/
Or if you know you want whichever one has an href that contains a parameter h= then you can use a selector like '.itemAnchor[href*="h="]' with .find(), in which case you don't need .last() or .slice():
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor[href*="h="]').attr('href');
Demo: http://jsfiddle.net/rtnNd/6/
Note though that this last method using the attribute-contains selector is picking up elements where the href has the text "h=" anywhere, so it works for your case but would also pick up hh=something or math=easy or whatever. You could avoid this and test for just h= as follows:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor')
.filter(function() {
return /(\?|&)h=/.test(this.href);
}).attr('href');
Demo: http://jsfiddle.net/rtnNd/7/