jQuery: get content / innerhtml onclick - javascript

If you click on a cell on this page, it loads the larger version of the image. I'm trying to achieve this same effect.
What I have gotten so far: http://jsfiddle.net/8mYW9/
First off I know having the "appear" <div> is redundant - is there a good way to utilize $(this) and appendTo(); instead?
Ultimately my idea is to grab the id of the anchor contained within the div that is clicked and to append it to the cell. What should I be doing...?

If you change the ID attribute to class for the appear elements you can do this:
$(document).ready(function() {
$('#appear').hide();
$('.links').click(function() {
var $this = $(this);//cache the $(this) selector since it will be used more than once
$this.children('.appear').html('item id: ' + $this.children('a').attr('id')).fadeToggle('slow');
});
});
Demo: http://jsfiddle.net/8mYW9/7/
BTW you can't have multiple elements with the same ID in a HTML document.

You could do that with:
$(document).ready(function() {
$('#appear').hide();
$('.links').click(function() {
$(this).append('<div>' + $(this).find('a:first').attr('id') + '</div>');
});
});
JS Fiddle demo.
Amended so that only one id is shown (others are removed before showing the latest):
$(document).ready(function() {
$('#appear').hide();
$('.links').click(function() {
$(this).closest('.container').find('.appended').remove();
$(this).append('<div class="appended">' + $(this).find('a:first').attr('id') + '</div>');
});
});
JS Fiddle demo.
Incidentally, it escaped my notice the first time, but with multiple elements sharing the same id you have invalid (X)HTML: an id must be unique within the document (citation: W3.org).
References:
attr().
closest().
find().
:first selector.
remove().

Try using class selectors instead. You've got duplicate IDs:
$(document).ready(function() {
$('.appear').hide();
$('.links').click(function() {
$(this).find(".appear").fadeToggle('slow', function() {
$(this).html('item id:')
});
});
});
http://jsfiddle.net/8mYW9/

Related

Appending ID without replacing original

I'm trying to append an ID to div elements, but it seems if there is already an ID it replaces the existing. I'm at a loss.
$(document).ready(function(){
$("div").each( function(i){
$(this).attr({ id: " num_" + ++i });
})
});
You can do it like below:
$(document).ready(function(){
$("div").each( function(i){
$(this).attr({ id: $(this).attr("id") + " num_" + ++i });
})
});
A div element can only have one identifier and this identifier must be unique.
So you can't append an id.
An element in html have atmost single id. To solve this problem use customised attributes. Start using 'data-id' and use them as the normal html attributes. If you want to add more ids you just increment number. like...
input id='name' data-id='username'

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Adding selectors into dynamically generated <li > element

I am trying to dynamically generate html content. However it seem like whenever I add tags or selectors to the li element, the code malfunctions
Correct behavior
Incorrect behavior
$('#btnName').click(function(){
var text = $('#inputName').val() + '<button>x</button>';
if(text.length){
$('<li name="somename" id="someid"/>', {html: text}).appendTo('ul.justList') // adding name tag and id selector cause error
}
});
$('ul').on('click','button' , function(el){
$(this).parent().remove()
});
Demo
Use the second parameter to set the other attributes rather than write them out in the tag. Also, you don't need to self-close the tag.
$('#btnName').click(function(){
var text = $('#inputName').val() + '<button>x</button>';
if(text.length){
$('<li>', {
html: text,
name: 'somename',
id: 'someid' + $('.justList li').length // for the sake of unique ids in the example
}).appendTo('ul.justList')
}
});

Use JQuery to target div container for hide/show div without using ID's

I have a script below and wanted to target the show/hide div as the check boxes are clicked without using ID's and restricting the hide/show feature within each container. Any suggestions?
Here is the fiddle. http://jsfiddle.net/45NRN/2/
And here is the jquery code.
$('.c-input').live('change', 'checkbox', function() {
var target = $(this).prev('.showHideDiv');
if ($(this).find('input:checked').length == 0) {
target.hide();
} else {
target.show();
}
});
This should do the trick
$('.c-input').live('change', ':checkbox', function() {
var target = $(this).closest('.c-input').prev().find('.showHideDiv');
if ($(this).find('input:checked').length == 0) {
target.hide();
} else {
target.show();
}
});
DEMO
Some comments:
Replaced 'checkbox' by ':checkbox'. Your selector finds tags with name checkbox (<checbox\>,that's not what you're looking for
this in your context is the checkbox and not the .c-input element. I changed the related selector to reflect this.
Or you could do this Working demo :- ) http://jsfiddle.net/P8UFL/
Issue was you are using .prev for the element which is inside another div --> wrap
Hence, to traverse through it correctly you probably need to do the prev on wrap and then find showHideDiv
Also HTML is bit invalid > chuck in /> with your checkboxes tag.
.live is depricated from 1.7 > Jquery version; alternative is .on just a note.
Hope this helps :)
Code
var target = $(this).prev('.wrap').find(".showHideDiv");

Get the id of the clicked-upon div

I want to select the id of the current div when I click on it in jQuery.
For example, say I have HTML like this:
<div class="item" id="10">hello world</div>
<div class="item_10">hello people</div>
When I click on the first div on .item class, I want to copy the id of the current div + adding to it the number (10), so it will be ("div id" + 10) equal to the second dev class = item_10.
I tried to use currentid = this.id; but it doesnt work :( !
First, note that id attributes starting with numbers are syntactically illegal in HTML4. If you're using id="10" make sure that you're using the HTML5 doctype (<!DOCTYPE html>).
It's hard to say why what you were doing didn't work without seeing your actual code. Presumably it is because you were registering for the event on a higher element (like the body) and this.id was the id of that higher element and not the element you clicked on.
In this case, you want to use the target property of the event to find what you clicked on. For example:
$(document.body).click(function(evt){
var clicked = evt.target;
var currentID = clicked.id || "No ID!";
$(clicked).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/
If you were registering on the specific elements instead, then this.id does work:
$('div').click(function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/1/
This is sub-ideal, however, because:
It makes many event handler registrations instead of 1, and
If additional divs are added to the document after this code is run, they will not be processed.
Under jQuery 1.7, you use the .on method to create a single event handler on a parent element with selectors for the kinds of elements you want to catch the event on, and have this set to them. In code:
$(document.body).on('click','div',function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/2/
I think you're trying to do something like:
$(".item").click(function(){
var id = $(this).attr("id");
var el = $(".item_" + id);
});
Now el is your second div.
You can simply use this.id
$('div').click(function() {
var divid = this.id;
alert($('.item_'+divid).html());
});
Demo
Something like this?:
$('div').click(function() {
theId = $(this).attr('id');
//Do whatever you want with theId.
});
This can be done as:
$('.item').click(function() {
var divId = $(this).attr("id");
});

Categories