The show/hide function is not working with the clone function - javascript

I have a problem triggering the show() and hide () function in jQuery when I use it together with the .clone() function.
There isn't any problem showing or hiding the first id but when it comes to a cloned id, showing or hiding doesn't work on it.
Here's a sample js of it:
var $country = $('#country')
$('#add-countries').on('click', function () {
$(this).before($country.clone());
});
$('#morelocal').on('click', function () {
$('#showzipcode').toggle();
$('#morelocal').hide();
});
$('#hidezipcode').on('click', function () {
$('#morelocal').show();
$('#showzipcode').hide();
});
Full jsfiddle here: http://jsfiddle.net/stan255/Wh274/7/

Since you are cloning the elements
It is better to use classes instead of ids because id of an element must be unique
And need to use event delegation to support dynamically added elements
so
<div>
<!-- use class instead of id -->
<a href="#" class='morelocal'>
Track ZIP/Postal code
</a>
<!-- use class instead of id -->
<span class='showzipcode'>
<input type="text" placeholder="e.g: 30196"/>
<a href="#" class='hidezipcode'>cancel</a>
</span>
</div>
then
var $country = $('#country')
$('#add-countries').on('click', function () {
var $clone = $country.clone().removeAttr('id');
$(this).before($clone);
$clone.find('.morelocal').show();
$clone.find('.showzipcode').hide();
});
//use event delegation
$(document).on('click', '.morelocal', function () {
var $div = $(this).closest('div');
$div.find('.showzipcode').show();
$div.find('.morelocal').hide();
});
$(document).on('click', '.hidezipcode', function () {
var $div = $(this).closest('div');
$div.find('.morelocal').show();
$div.find('.showzipcode').hide();
});
Demo: Fiddle, Fiddle2

Related

JQuery - Get the ID attribute of li element

I have a pagination control who's <li> elements are dynamically set and assigned a ID. Using jQuery I am then attempting ti retrieve these set ID's
<div class="col-lg-12 text-center">
<ul class="pagination" id="pagHolder"></ul>
</div>
<script>
$(document).ready(function () {
//*****Logic for setting 'mainArrayHolder'*****
for(var i = 0; t < mainArrayHolder.length; i++)
{
$('#pagHolder').append('<li id="'+i+'">'+ i +'</li>');
}
});
</script>
The Issue I have is I am receiving an 'undefined' error when using the following function:
$(this).click(function(){
var id = $(this).attr("id");
alert(id);
});
I understand this is because 'this' is looking at the whole of the DOM rather than just the <li> elements. How do I set this code so it will get the id attribute of any of the <li> elements a user clicks?
You need to update the selector for your click event.
The following should work:
$('#pagHolder').on('click', 'li', function() {
alert( $(this).attr('id') );
});
Notice that we use the on() function, and delegate the event to any li which exists now (or in the future) as a child node of pagHolder.
Alternatively, you don't need to use jQuery's attr() function inside of the event handler, since this relates to the DOM node itself, you can access its properties directly, for example:
$('#pagHolder').on('click', 'li', function() {
alert( this.id );
});
You are appending li's to #pagHolder list, so you could get ids like this, for example:
$('#pagHolder').on('click', 'li', function() {
var id = this.id;
alert(id);
});

Making this JS code unobtrusive. Writing an event listener for unknown id

I've been building out the functionality for this UI. These are a pair of tabs I want to write a listener for, to make my js unobtrusive. It was blocking me from going forward. Now that I'm refactoring, it's time to fix it. I want to write an event listener that gets the id of the tab that was clicked, and assigns it to a variable. This is what I have:
<ul id="gal">
<li class="glyphicons camera active" onclick="pullActive(this.id);" id="viewAll"><a href="#" ><i></i> View all photos <strong>(43) </strong></a>
</li>
<li class="glyphicons circle_plus tab-stacked" onclick="pullActive(this.id);" id="addPhotos"><i></i> <span>Add Photos</span>
</li>
</ul>
function pullActive(id){
// gets the class for that id
var getClassy = document.getElementById(id).className;
findClass(getClassy, id);
loadNew();
}
without jQuery you would have to do
var item = document.querySelector("#gal");
item.attachEventHandler("click", function(ev) {
if (ev.target.tagName === "LI") {
var id = ev.target.id;
// ...
}
});
In jquery (as you tagged your question like this) it would look like this
$(function() {
$("#gal").delegate("li", "click", function() {
var id = this.id;
// ...
});
});
jQuery solution:
$('#gal li').on('click', function () {
var className = $(this).attr('class');
var id = this).id;
console.log(className, id);
});
Vanilla solution:
[].forEach.call(document.querySelectorAll('#gal li'), function (glyphicon) {
glyphicon.addEventListener('click', function () {
var className = glyphicon.className;
var id = glyphicon.id
console.log(className, id);
});
});
Here is a fiddle containing both examples.
Using jQuery, this would be
$( document ).ready(function() {
$( '#gal' ).on( 'click', 'li', function() {
var id = this.id
});
});
The benefit of this approach is that you only have one event handler (defined on the ul) vs. having one for each li. Hope this helps.

How to decide which element is being clicked in jQuery?

I have more similar elements in HTML which are being added continously with PHP. my question is the following:
With jQuery, I would like to add a click event to each of these <div> elements. When any of them is being clicked it should display it's content. The problem is that I guess I need to use classes to specify which elements can be clickable. But in this case the application will not be able to decide which specific element is being clicked, right?
HTML:
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
jQuery try:
$("test").on("click", function()
{
var data = ???
alert(data);
});
UPDATE - QUESTION 2:
What happens if I'm placing <a> tags between those divs, and I want to get their href value when the DIV is being clicked?
I always get an error when I try that with this.
this refers to the element triggering the event. Note that it is a regular js element, so you'll need to convert it to a jQuery object before you can use jQuery functions: $(this)
$(".test").on("click", function()
{
var data = $(this).text();
alert(data);
});
Like this:
$(".test").on("click", function(event)
{
var data = $(event.target);
alert(data.text());
});
this variable contains the reference of current item
$(document).ready(function() {
$(".test").click(function(event) {
var data = $(this).text();
alert(data);
});
})
;
The class selector in jquery is $(".ClassName") and to access the value, use $(this) as such:
$(".test").on("click", function(){
var data = $(this).text();
alert(data);
});
You can use this inside the function which mean clicked div
DEMO
$(".test").on("click", function () {
alert($(this).html());
});

Jquery click event on <a> tag not firing properly

I'm trying to catch the jquery click event on an tag with a class, but its not firing.
HTML: (there's 10 blocks)
<div id="block1">
<div class="slideshow">
<a class="popup" href="#imgform">
<img src="<?php echo 'core/controllers/foto.php?o=1'; ?>" title="1" width="271px" height="413px">
</a>
</div>
</div>
<div id="block2">
<div class="slideshow">
<a class="popup" href="#imgform">
<img src="<?php echo 'core/controllers/foto.php?o=2'; ?>" title="2" width="200px" height="129px">
</a>
</div>
</div>
jQuery:
$(document).ready(function() {
var $popup = $('a.popup');
$popup.live('click',function(){
var id = $popup.parent().parent().attr('id');
id = id.substring(5);
alert(id);
$.get('index.php?o='+id, function(data) {
$popup.fancybox({
//do stuff
});
});
});
});
The alert is always returning 1 for some reason.
Try this,
$('a.popup').on('click',function(){
alert($(this).parent().parent().attr('id')); // to check whether it is firing....
});
This may help you.
Use .on() as of jQuery 1.7.
Make use of the data parameter in your AJAX calls this may ensure proper escaping of the query parameters. If you still insist doing it manually you can use $.param.
In your specific case you can cache lot of things. Although, this may not work for dynamically added elements after loading is complete.
$(document).ready(function() {
$('a.popup').each(function() {
var $this = $(this);
var id = $this.parent().parent().attr('id').substring(5);
$this.click(function() {
$.get('index.php', {
o: id
}, function(data) {
$popup.fancybox({
//do stuff
});
});
});
});
});​
Moreover, using data-* attributes you can easily drop the id attribute parsing and have a cleaner markup.
Using a block classname.
Adding a data-block-id attribute.
You should definitely be using classnames to style elements and not IDs.
<div class="block" data-block-id="1">
<div class="slideshow">
<a class="popup" href="#imgform">
<img src="<?php echo 'core/controllers/foto.php?o=1'; ?>" title="1" width="271px" height="413px">
</a>
</div>
</div>
$(document).ready(function() {
$('a.popup').each(function() {
var $this = $(this);
var id = $this.parent().parent().data("block-id");
$this.click(function() {
$.get('index.php', {
o: id
}, function(data) {
$popup.fancybox({
//do stuff
});
});
});
});
});​
use this
$(document).ready(function() {
$('a.popup').on('click',function(){
var id = $(this).parent().parent().attr('id');
id = id.substring(5);
alert(id);
});
});
In you event handler, you need to use the event that was actually clicked.
$('a.popup').click(function() {
var $id = $(this).parent().parent().attr('id');
...
});
Please note that as of jQuery 1.7, the .live() method is deprecated. Use .on() or .click() to attach event handlers.
Use:
$(document).ready(function() {
var $popup = $('a.popup');
$popup.live('click',function(){
var element = $(this);
var id = element.closest('[id^="block"]').attr('id');
id = id.substring(5);
alert(id);
$.get('index.php?o='+id, function(data) {
element.fancybox({
//do stuff
});
});
});
});
If you are on jQuery 1.7 +, Use:
$(document).on('click', 'a.popup' ,function(){
//do Stuff
});
I think you want to bind the click callback to your links. You'll also probably want to prevent the default behaviour, otherwise your page will reload.
$(".popup").click(function(){
var id = $(this).parent().parent().attr('id')[5];
alert(id);
});​
Also, using classes effectively could cut out most of those parent calls, before they get out of hand. For example.
<!-- Make the head div belong to class "head" -->
<div id="block1" class="head">
<div class="slideshow">
<a class="popup" href="#imgform">
$(".popup").click(function(){
// If you click the first link, you'll get "block1" in the alert.
var id = $(this).parents(".head").attr('id');
alert(id);
});​
I was having similar problem where i wasnt able to get i click I tried on() its better than live().
Check this link for more http://api.jquery.com/on/ In this page check out the last three examples at the end of the page you might get a better solution.
You can use
$(document).on("click", "$popup", function() {
var id = $popup.parent().parent().attr('id');
id = id.substring(5);
alert(id);
$.get('index.php?o='+id, function(data) {
$popup.fancybox({
//do stuff
});
});

How can I manipulate dynamically created elements wth jquery?

I am a jquery newbie and i am creating boxes with jquery and then "deleting" them. But I want to use the same code to delete the box in the scope of the created element and the scope of a already created element.
Html:
<button id="create">Cria</button>
<div id="main">
<div class="box">
<a class="del-btn" href="#">Delete</a>
</div>
</div>
JS:
var box = {
create: function() {
var box = $('<div class="box">');
var delBtn = $('<a class="del-btn" href="#">Delete</a>');
box.appendTo('#main');
delBtn.appendTo(box);
},
destroy: function(elem) {
elem.fadeOut();
}
}
function deleteBox () {
}
$(function() {
$('#create').click(function() {
box.create();
});
$('.del-btn').click(function() {
var elem = $(this).parent();
box.destroy(elem);
return false;
});
});
If I put the delete event inside the create click event, I just can delete the dynamically created element. If I put it outside, then I can just delete the element in the HTML. I know this is a simple question, but I can't figure out how to solve it. Thanks
You can use delegated-events approach:
$("#main").on("click", ".del-btn", function() {
var elem = $(this).parent();
box.destroy(elem);
return false;
});

Categories

Resources