Click on an object, get another object? - javascript

On click I get an objects id.
The id will be something like 'about-me'.
Now in the on click function I want to target the object that's called 'content-about-me'.
How can I do this? Ive tried this with no luck:
$('.sub-nav').on('click', function(){
$('#content-'$(this).attr('id'));
});

You have to concatenate the id with the prefix content-:
$('#content-' + this.id);
I also replaced $(this).attr('id') with the equivalent but shorter this.id.
Keep in mind that instead of doing this, it might be a good idea to have the full id of the "other" element stored somewhere on the click target. For example:
<div class="sub-nav" id="foo" data-other-element="content-foo">...</div>
And then do
$('.sub-nav').on('click', function(){
var $other = $("#" + $(this).attr('data-other-element-'));
});
This code is DRY, so if you decide to change the id tagging scheme your JS code will not need to change as well.

Related

This jQuery toggleClass behaviour seems strange, am I doing this correctly?

I have a CSS rule for hiding elements with a class="hidden" and I'm using jQuery to toggle this class on and off on whatever ID i click on so I can make elements disappear.
Why does this not work?
$(this).attr('id').toggleClass("hidden");
but this does?
var x = "#" + $(this).attr('id');
$(x).toggleClass("hidden");
I know that the id is being taken correctly on the first example, but it seems that to toggle the class I have to add a "#". I haven't seen any examples of others having to resort to this so I'm wondering what madness I have here.
Many thanks
$(this).attr('id').toggleClass("hidden");
You are chaining events here. $(this).attr('id') already returns you a string. So you are technically doing "someid".toggleClass("hidden") which doesn't makes sense.
In your second example, you are actually selecting the same element again via id and firing your method, which is right
.attr('id') returns a string, not an element.
Let's pretend your element has an ID of myThing. Here's what your code translates to:
// 1
"myThing".toggleClass("hidden");
// 2
var x = "#myThing";
$("#myThing").toggleClass('hidden');
But really, if you're getting the ID from this, there's no reason to extract the ID in the first place. Just use this directly.
$(this).toggleClass('hidden');
You can simply use:
$(this).toggleClass("hidden");
$(this) is the actual element you're working with, so you can use this to directly toggle classes with.
In your examples, $(this).attr('id') is a string, and not an element.
This code works, because you're taking the ID (As a string), and selecting the ID on the webpage.:
//Store the id into a string
var x = "#" + $(this).attr('id');
//Pass the ID back into jQuery, and find the element
$(x).toggleClass("hidden");

jQuery '#' + data("target") pattern

I've seen this a bunch:
Click me
<div id="content">And something will happen here</div>
With JS like this:
$("#trigger").click(function(){
$("#" + $(this).data("target")).hide();
})
It looks a little weird to me to be doing this string concatenation to create selectors which are then used to get the target element. Is there a better pattern in Javascript (with jQuery available) for setting up handlers on one element which need to know about another target element?
Why you do string concatenation just store the id with #
Click me
$("#trigger").click(function(){
$($(this).data("target")).hide();
})
Similarly you can store any selectors as is in data-target say for ex:- .tab1 etc so that you do not have to perform string concatenation again inside the click or any event.
You can simply use
$('#content').modal('toggle');
Any where in you're code to initiate the modal show and hide,
You can use even "show"/"hide" functionality directly.
I assume you're using Bootstrap and one of the latest versions of jQuery.
Enjoy !
Why not do something like this, a much better approach in my opinion:
// Set the target
$("#trigger").data('target', $('#content'));
// Get the target
$("#trigger").click(function(){
$(this).data("target").hide();
})
If you're setting it from the backend, I would include the hash with the attribute value as others have suggested.
Click me
$("#trigger").click(function(){
var target = $(this).data("target");
$(target).hide();
})
You always have the option to build the selector, looks a bit nicer than concatenating the string inside the selector.
$("#trigger").click(function(){
var selector = "#" + $(this).data("target");
$(selector).hide();
});
A little nicer, not sure if it's what you're looking for.
I would skip the data- completely, thus allowing graceful degradation.
Click me
<div id="content">And something will happen here</div>
with
$("#trigger").click(function(e){
e.preventDefault();
$( $(this).attr("href") ).show();
// note, i'm purposly not using this.href due to a bug in IE that would return the entire href rather than just the hash
})
$(this).attr('data-target', '#myTarget');
this worked for me

jquery- store id of clicked link in variable

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);
});

jQuery .click() event for multiple div's

I have some search results that I'm outputting that are of this form:
<div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?
Here's how I'm getting the HTML from above:
$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;
var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
I tried
$('div').click(function(){
alert(this.id);
});
and the alert says "searchresults" (no quotes).
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.
$("#searchresults").delegate("div", "click", function() {
console.log(this.id);
});
See .delegate
You can't have the same ID on multiple tags. You will have to fix that. You can use the same class, but there can only be one object in the page with a given ID value.
this.id will fetch the id value of the item clicked on and this should work fine once you get rid of conflicting IDs:
$('div').click(function(){
alert(this.id);
});
This code should be something this:
var search_results="<div id='result'" + video_id + " title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append(search_results);
to coin a unique id value for each incarnation and append will just take the string - you don't need to turn it into a jQuery object.
you could get the title using $(this).attr("title").val()

Appending a string variable in jQuery

I'm not sure if I have the syntax correct in the code below, I'm trying to append a var to a string parameter within the find function. I'm trying to search for a unique id within each input element of a particular form.
//Get value attribute from submit button
var name = $('#myForm').find('input#submitThis').val();
//Other code that manipulates the name variable
//Submit button in hidden form
$('.submitLink').click(function(){
$('#myForm').find('input#'+name).click();
return false;
});
The element with a submitLink class is supposed to be tied to the submit button in the form. I don't think I have the syntax correct though, when I go back and click the element that has the submitLink class, nothing happens.
The syntax appears fine to me. To be sure the selector is what you are expecting it to be, you could do something like this:
$('.submitLink').click(function() {
var selector = 'input#' + name;
alert(selector);
/* rest of the code */
});
Try adding an alert to test the var inside the event handler (and to see that the handler is fired). Also, if you are looking for an element with a specific id you don't need to include the element type. Like this:
$('.submitLink').click(function (event) {
event.preventDefault();
alert(name);
$('#' + name, $('#myForm')).click();
});
NOTE: If you are trying to find an element by its name rather than ID you must use $("input[name='foo']").

Categories

Resources