Event delegation works with document but not with parents - javascript

I have the following HTML code, and i am currently trying to add the 'selected' class when a photo is clicked, and to remove the class when it is clicked again.
<div id="container">
<h1>Photo Gallery</h1>
<div id="gallery">
<div class="photo">
<img src="photos/skyemonroe.jpg">
<div class="details">
<div class="description">The Cuillin Mountains, Isle of Skye, Scotland.</div>
<div class="date">12/24/2000</div>
<div class="photographer">Alasdair Dougall</div>
</div>
</div>
//Repetitions of the photo class.....
</div>
<a id="more-photos" href="pages/1.html">More Photos</a>
</div>
I am currently using the following jquery code to bind an event handler to the photo's ancestor so that when more pictures are appended to the page when clicking the more photos button, the jquery code will still work with these newly added pictures.
jQuery
$('#gallery').on('click','.photo',function(){
$(this).toggleClass('selected');
});
The jQuery code above DOES NOT work when i try using the #gallery, NOR does it work when i try using #container.However, the code works when i use $(document) for the event delegation.
I can't seem to figure out why binding the event handlers to the parent elements do not work, but binding it to the document itself makes it work.
Would appreciate any insights into the matter
EDIT: Added the jsfiddle here http://jsfiddle.net/744cX/ ( The code works in the fiddle, but does nothing on my laptop, and i can't seem to figure out why)

You can listen event on '.photo' class
<div class="photo" onclick="$(this).toggleClass('selected');">

I forked your fiddle and as can be seen here:
http://jsfiddle.net/6Qz8C/1/
$('#gallery').on('click','.photo',function(){
$(this).toggleClass('selected');
});
I did:
when the nextpage event is fired, append a new photo.
add the event delegation when the document is ready.
set the delegator to the #gallery

Related

addEventListener 'click' event not recognizing click and not calling function

EDIT: Removed all question content because I wiped my JavaScript clean and started from scratch and it worked. As far as I can tell I did not do anything different from the first time. I'm still not sure why it wasn't working before, but it is working now. See answer below for working addEventListener click/toggle event.
The argument to an event listener is the event. If you want the element the event listener is attached to, reference the currentTarget of the event.
function activateOffCanvasNav(e) {
e.currentTarget.classList.toggle('active');
}
If you try to do e.classList.toggle instead, like you're currently doing, you'll get a TypeError, since events don't have a classList property.
Working live demo:
document.getElementById('hamburger-icon').addEventListener('click', activateOffCanvasNav);
function activateOffCanvasNav(e) {
console.log('here')
e.currentTarget.classList.toggle('active');
}
.active {
background-color: green;
}
<header>
<!-- small screens only -->
<div class="small-nav-header">
<a id="nav-toggle" href="#!">
<div id="hamburger-icon" class="hamburger-icon">
<div class="bar1">bar</div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</a>
</div>
</header>

jQuery closest() remove() on <a> doesn't work?

Please see this page which has this code:
<div class="pure-control-group query-brand-by-column">
<!-- somethings else -->
<div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
X
</div>
</div>
Clicking the X link should remove its ancestor div.query-brand-by-column as a whole but somehow it's not working. I've checked jQuery docs and this answer and the code seems absolutely all right to me but it simply doesn't work. Any idea?
this in href doesn't refers to anchor element, thus it doesn't work. It refers to window.
You should bind element event handler using jQuery.
Script
$(document).on('click', '.pure-button danger' function(e) {
e.preventDefault();
$(this).closest('.query-brand-by-column').remove();
});
HTML
<div class="pure-control-group query-brand-by-column">
<!-- somethings else -->
<div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
X
</div>
</div>
I will not recommended, However you can use inline onclick handler.
<a onclick="$(this).closest('.query-brand-by-column').remove();" href='#' class="pure-button danger">X</a>
Here is your answer, Enjoy
X
Detach your javascript from your html and remove your item with a click event, right now you aren't triggering any click events:
<script>
$(function(){
$('.pure-form').on('click','.query-brand-by-column a',function(){//this will create and delegate your click event to work on dynamically created items
$(this).closest('.query-brand-by-column').remove();
});
});
</script>

jQuery parent(); function removeClass(); not working (bug)

I have a portfolio where I list portfolio items.
I have classes so when you click the item, it has an effect.
For some reason, when I click the minus button, it doesn't remove the class 'on'.
Here is the jQuery:
$('.portfolio-item').click(function() {
$(this).addClass('on');
});
$('.minus').click(function() {
$(this).closest('.portfolio-item').removeClass('on');
});
and here is the element set up:
<div class="portfolio-item" style="margin-top: 5px; ">
<div class="overlay">
<h1>LOW POLY ISLANDS</h1>
<h3>LOW POLY</h3>
</div>
<div class="about">
<h1>LOW POLY ISLANDS</h1>
<h3>LOW POLY</h3>
<div class="descrip">
This is a low poly island make in Blender and edited in Photoshop.
</div>
<div class="minus"></div>
<div class="plus"></div>
</div>
<img src="https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/57909c29180525.55fc4b1875c26.png" width="100%" />
</div>
How do I fix this - I want to be able to remove the class 'on' when I click on 'minus'.
When you click your minus it removes the class on. However, at the same time, as minus is located within portfolio-item, it triggers its click event and applies this class back.
You can use e.stopPropagation() to disable this behaviour.
According to documentation, e.stopPropagation
prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Here is the working JSFiddle demo. It looks awful, but demonstrates the functionality.
you need to use e.stopPropagation()
$('.minus').click(function(e) {
e.stopPropagation();
$(this).closest('.portfolio-item').removeClass('on');
});
DEMO

jQuery in Meteor having trouble finding DOM selectors

Here is the template whose DOM elements I am trying to control:
<template name='libraryTemplate'>
<div class="container-fluid library_container">
<div class="row">
<div class="col-sm-6">
<h1 id='maglens_library_header'>MY LIBRARY</h1>
<div id='library_page_break'></div>
<div id='folders_text'>
Folders:
</div>
</div>
<div class="col-sm-6">
<a class='button-text btn' id='add_new_button'>ADD NEW</a>
</div>
</div>
<div class="row">
<div class="col-sm-3 folders" id='google_drive_thumbnail'></div>
</div>
</div>
</template>
And here is the jQuery Im using to do so. My $('body') selector works fine, and my log statement just inside $(document).ready() behaves correctly, but why can't I target the selector $('.folders')? Upon inspection of the DOM, I can see exactly where the code is, but it's like jQuery thinks it doesnt exist?
$(document).ready(function(){
console.log('document ready');
$('.folders').on('click', function(){
console.log('folders clicked');
})
// $('body').on('click', function(){
// console.log('body clicked');
// })
});
I don't see any selectors named folders.
I do see <div id='folders_text'>.
That's why your body event fires but your other one doesn't.
Secondly, you should be using template events, you're working with Meteor now.
Template.libraryTemplate.events({
'click .folders': function() { console.log('clicked') }
})
I'd definitely recommend using the meteor events as everyone else suggested.
What you had actually works, it is just since the div with the "folders" class has no content, the div is very small (unless you have a height attribute on ".folders" or "#google_drive_thumbnail") and thus very hard to click on. Inspect element on the div and you'll see the size

function work without class that call for function

I have two classes and a function that works with one of them
$('.div-image').click(function(){ // image zoom
$('#image').attr("src",img_src);
$('.div-image').attr('class','div-image-big');
});
and html something like:
<div class="div-image">
<div id="wrapper">
<img id="image" src="image.jpg">
</div>
</div>
Why after first click on the image or (div .div-image) my class div-image is changing to div-image-big. But if we click once more the function $('.div-image').click(function(){...} will execute again. The question is why so? I don't need this behavior. I want that this function work only when class is div-image not div-image-big. Thanks.
The event handler is bound on the element, not the class. Which elements it is bound to is decided based on the class they have at the time that the event is bound, so changing the class later doesn't change which elements have the event handler.
If you want the event handler to react to the class, you should bind a delegate to the a parent element. That way the event bubbles to the parent element, and the delegate handler will check for the class at that moment. Example:
HTML:
<div class="image-container">
<div class="div-image">
<div id="wrapper">
<img id="image" src="image.jpg">
</div>
</div>
</div>
Javascript:
$('.image-container').on('click', '.div-image' ,function(){ // image zoom
$('#image').attr("src",img_src);
$('.div-image').attr('class','div-image-big');
});

Categories

Resources