I'm trying to... God, this is hard to explain.
I got an array called 'triggers' with these variables:
"#1_trigger","#2_trigger","#3_trigger"
And inside a jQuery each(), I create another variable called 'targets' that copies everything from 'triggers' and replaces all _trigger to _target. I then append the 'triggers' to anchor IDs, and 'targets' to hidden div IDs.
What I want to do, is this: When hovering a _trigger, the _target will show up. I've managed to make it work with only one variable, but not with multiple.
As I said, it's kind of hard to explain what I want to do in text, so here's a demo and my progress so far:
http://jsfiddle.net/WJWe3/6/
I've been stuck with this one for too many hours now, please help!
1st, do not name them with a # since you use that in the actual id. (you can add the # in when you need to seek them with jquery)
After that step the code you need is
$("#experiment a").hover(function(){
$( '#' + this.id.replace('_trigger', '_target') ).show();
}, function(){
$( '#' + this.id.replace('_trigger', '_target') ).hide();
});
This should be outside of the each loop since it automatically finds the relevant target.
You were also missing a sign = at the point that you assigned the id to the divs.
demo at http://jsfiddle.net/gaby/WJWe3/14/
Something like this maybe?
http://jsfiddle.net/WJWe3/11/
When you set the id for an element, it should not start with #. It's only when you use it as a selector in jQuery that it starts with #.
However, you don't even need to use the id. Create the a and div element as objects instead of as a string, then you can hook up the hover event directly to the link, and access the div directly, instead of trying to find it after adding it to the page.
jsfiddle.net/WJWe3/16/
var triggers = ["1_trigger", "2_trigger", "3_trigger"];
jQuery.each(triggers, function(i, val) {
var target = $('<div/>', { className: 'hidden' }).text('You found me!');
var link = $('<a/>', { href: '#' }).text(val).hover(function(){
target.stop().fadeTo("normal", 1.00);
}, function(){
target.stop().fadeTo("normal", 0.00);
});;
$("#experiment").append(link).append(target).append("<br/>");
});
here's how i would do this
http://jsfiddle.net/WJWe3/15/
<div id="experiment">
<p><a>test 1</a> <span class='hidden'>hidden 1</span></p>
<p><a>test 2</a> <span class='hidden'>hidden 2</span></p>
<p><a>test 3</a> <span class='hidden'>hidden 3</span></p>
</div>
...
$('#experiment a').hover(
function(){
$(this).siblings('span').stop().fadeTo("normal",1);
},
function(){
$(this).siblings('span').stop().fadeTo("normal",0);
}
);
Here's another that works.... Just for fun.
http://jsfiddle.net/WJWe3/18/
Related
I have three article tags that each have 1 section which I need to animate to appear i.e height from 0px to whatever px. Each article has an ID what is the most efficient way to have an on click event for each one without writing a separate function for each individual id i.e is there a 'get clicked article's id' type method?
Thanks
This is what I would do,
jQuery:
$('.art h1').on('click', function() {
$(this).parent().find('p').stop(true).slideToggle();
});
html:
<div class="art">
<h1>Some article stuff</h1>
<p>text goes here</p>
</div>
fiddle: JSFIDDLE
If you want it to slide up and have only one open at a time then you can make a minor edit like so,
jQuery:
$('.art h1').on('click', function() {
$('.art p').slideUp();
$(this).parent().find('p').stop(true).slideToggle();
});
fiddle: Only one active JSFIDDLE
You can combine multiple selectors with a comma:
$('#id1,#id2,#id3').click(function() {
$(this).animate(...);
});
...or you could add class="something" to each element and just select that:
$('.something').click(function() { ... });
Use a class for the click event, instead of ids .. you can then use the id or some other attribute to identify which article to expand.
$('.someClass').click(function() {
thisId = $(this).attr('id');
$('#whereTheSectionsAre').find('.active').removeClass('active').next().slideUp(400);
$(thisId+'article').toggleClass('active').next().slideDown(400);
return false;
});
You can check some examples here, mainly if the id's are dynamic:
http://jsbin.com/uzEkiQa/3/
The first approach is the one already suggested, but with dynamic id's:
$('div[id^="id_"]').text("Changed by regexep");
The second one if your matching is a bit more hardcore uses filter:
var reg = new RegExp(/id_\d+/);
$('div[id^="id_"]')
.filter(function(index, item) {
return reg.test(item.id);
})
.text("Changed by filter and regexp");
After the selection you can apply the behaviours you want. Check the JSBin to play around.
I'm building a recipe saving application where I have a form that looks like this http://jsfiddle.net/LHPbh/.
As you can see, I have a set of form elements contained in an <li>. You can click Add Ingredient and have more li's added to the field.
My problem is:
The first li is the only one that deletes. If you click Add Ingredient, and then try and delete that one, nothing works?
Is there a way to not have the first li have a delete by it, but all subsequent li's have a delete link on the side? (Just because there should always be at least one ingredient?)
When you call clone(), it isn't duplicating the events. You need to call clone(true) in order for it to do this, as explained in the documentation.
You did not put an event listener on the cloned elements. Also, you should not give the "delete"-link its own id, as those need to be unique.
To make the first ingredient have no delete button, just don't include one in your markup but only dynamically create and append them to the cloned elements:
var deleteButton = $("<a class='float-left'>Delete</a>").click(deleteThis);
$('ul#listadd > li:first')
.clone()
.attr('name', 'ingredient' + newNum)
.append(deleteButton)
.appendTo('ul#listadd');
function deleteThis() {
var li = $(this).closest('li')
li.fadeOut('slow', function() { li.remove(); });
}
Demo at jsfiddle.net
http://jsfiddle.net/LHPbh/2/
$('.deleteThis').live("click", function () {
var li = $(this).closest('li')
li.fadeOut('slow', function() { li.remove(); });
});
It is answer to the 1. point. The problem was, that the eventhandler binding did not happen in newly created elements, because this code runs only on the load of the page. This can be solved by using .live(). And an other problem was, that id-s must be unique. So instead id, here you can use class .deleteThis.
http://jsfiddle.net/LHPbh/19/
This has added answer to the 2. point:
if ($("#listadd li").length == 1) {
return;
}
If the list only contains 1 li element the rest of the callback will not run.
You are adding items that are added to the DOM dynamically, thus jQuery can't access them :)
In this case you can use the following code:
$(document).on('click', '.selector', function(e) {
//code here
});
Secondly, you were loading a quite old version of jQuery.
Thirdly, you were trying to select an element with an ID that already existed, and ID's can only exist one time. I've changed it to a class in the updated example.
Lastly, you were defining the class of the link twice like this:
<a class='float-left' id="deletethis" href='#' class="deletethis">Delete</a>
That also gave a problem, so I changed it to correct markup like this:
<a class='float-left deletethis' href='#'>Delete</a>
Good luck :) I've updated your jsFiddle here:
http://jsfiddle.net/q4pf6/
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.
I have a set links on a page like this
<a href='' class='contact' data-index='1'>One</a>
<a href='' class='contact' data-index='2'>One</a>
<a href='' class='contact' data-index='3'>One</a>
I am trying to return the value of the data-index of each link when it is clicked but Whenever I click on each link, the data-index of the first link is always returned because jQuery will select all the links with class = 'contact' on the page.
I am trying to figure out how to select the data-index of the clicked link.
I use something like this :
var m_data = $("a#contact").attr("data-index");
I've also tried something like this :
$("a#contact").click(function() {
var data = $(this).data('index');
});
but data was undefined.
Please how do I do this? Thanks.
# is an id selector. Which should be unique. When using id-selector in jQuery, it will always return the first element, since it isn't expecting to find any more items.
Change your code
<a data-index="1" class="contact">Whatever</a>
$("a.contact").click(function() {
var data = $(this).data("index");
});
And as Eskat0n mentions, since jQuery 1.6, jQuery automatically gets data- attributes via the data() method
Since jQuery 1.6.x values of data attributes populates into data associated with element by jQuery, so if your html look like <a class="contact" data-index="5"></a> your code should work:
$("a.contact").click(function() {
var data = $(this).data('index');
// data is "5"
});
As you can see there is correction: # used to get element by id which needed to be unique. Use class intead of id for multiply link elements.
$("a.contact").each(function()
{
$(this).click(function()
{
var data = $(this).attr('data-index');
});
});
You want .index(). This fiddle indicates how it can be used if the list of links is the only list on the page and also if there are other DOM elements mixed in with the links.
This should be basic, but for some reason its not working for me. I just want to store the id when a link that has a certain class is clicked in a variable so as an example:
Some link
I would want jquery to get the id of the link above and store it in a variable. I have tried $this.attr("id") and $this.id, but non of this worked.
This is what I have for the jquery:
$(".only_this_class").click(function() {
var clickedId= $(this).attr("id");
alert(clickedId);
});
I just get "undefined" every time.
I removed the space between this and _class in class="only_this _class" and it is working for me.
Try this here
Please have a look at jQuery Selectors
If you have two classes in your HTML then the syntax is different:
$('.classA.classB')
Have a look at How can I select an element with multiple classes?
NAVEED is right, if you remove the space it works, because if there is a space HTML will put two classes on the element: only_this and _class.
If you are in fact looking for two different classes, you should replace the space with a dot to make it work properly, as in $(".only_this._class")
$(".only_this _class") this selector will look for _class tag in .only_this element. May you are looking for $(".only_this") which will select element which has this class. Try this.
$(".only_this").click(function() {
var clickedId= $(this).attr("id");
alert(clickedId);
});