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

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>

Related

Open modal window with Jquery

I have a working modal which has the following code:
<!-- modal code -->
Follow
<!-- modal window -->
<div id="ex1" style="display:none">
<p> Please <%= link_to "Login", new_user_session_path %> </a> to Extend. </p>
</div>
I made a div class named "extend-button". I want to show the modal by clicking on that div.
<li class="extend-button"> Extend </li>
$(document).ready(function(){
$(".extend-button").mouseup(function(){
$("#ex1").dialog('open');
});
});
This isn't working.
Consider using the click() function. Otherwise all appears well, assuming dialog('open') works as intended. Add a console log to ensure the click event handler is working to help you debug.
$('.extend-button').click(function (e) {
console.log('clicked');
$("#ex1").dialog('open');
});
You need to first move all your jquery codes into the <script> tag. Then replace $(".extend-button").mouseup with $(".extend-button").click.
The difference between a mouseup event and a click event is that, with a mouseup event, you can click your mouse, hold it, and drag the mouse pointer any and everywhere before releasing the mouse to trigger a mouseup event. A click event requires the mousedown and mouseup event to happen on the same element.
The normal expectation is that a click requires both the mousedown and mouseup event.
The following change in HTML made my day. No jquery was needed.
Extend
First of all, make sure you are including the JQuery UI library and CSS file in the <head> of your page.
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
HTML:
<!-- modal code -->
Follow
<!-- modal window -->
<div id="ex1" style="display:none">
<p> Please <%= link_to "Login", new_user_session_path %> </a> to Extend. </p>
</div>
<li class="extend-button"> Extend </li>
You also need to make sure you are wrapping the code in <script> tags. As #elzi mentioned may be better to use a .click() event.
<script type="text/javascript">
$(function(){
$(".extend-button").on("click", function(){
$("#ex1").dialog('open');
});
});
</script>

Event delegation works with document but not with parents

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

jQuery remove div onclick

I can't seem to get my jQuery right to remove a div when I delete something
Code is:
<div class="amend_order" data-item_key="1367264719mz7">
<p>Home Made Ice Cream</p>
<p class="small_text">Pistachio</p>
<p>
<a class="edit_item ui-link" href="javascript:void(0);">Edit</a>
----
<a class="deleter ui-link" href="javascript:void(0);">Delete</a>
</p>
</div>
I have tried using
$(this).closest('div').remove();
unfortunately this does not work.
Basically there is a list of several divs and I just want them to disappear when clicked.
If your container divs are dynamically added, you need to use event delegation. Try this:
$("#container").on("click", ".amend_order .deleter", function () {
$(this).closest("div").remove();
});
DEMO: http://jsfiddle.net/m6jVP/
If they're added dynamically, then the event binding won't actually find any elements and therefore won't execute when they're clicked. This event handling runs for any elements inside of #container that match the selector .amend_order .deleter when they are clicked.
You can replace #container with a selector that matches a stable (static) element containing these divs you're targeting, using document if necessary.
HTML
<div class="amend_order" data-item_key="1367264719mz7">
<p>Home Made Ice Cream</p>
<p class="small_text">Pistachio</p>
<p>
<a class="edit_item ui-link" href="javascript:void(0);">Edit</a>
----
<a class="deleter ui-link" href="javascript:void(0);">Delete</a>
</p>
</div>
JS
$('.deleter').on('click', function(){
$(this).closest('div').remove();
})
Live sample http://jsfiddle.net/Ny346/
Try pointing to the div:
$('div.amend_order').click(function(){
$(this).remove();
});
or when clicking on the delete button:
$('a.deleter.ui-link').click(function(){
$(this).parent('div').remove();
});
Try this:
$('.deleter').on('click', function(){
$(this).parent().parent().remove;
})
Live Sample

Fancybox 2.0 not working, very simple first test

My page is at www.danielcw.info.
At the bottom I am calling:
$(document).ready(function() {
$("#single_1").fancybox({});
});
On:
<div id="single_1">
TESTTESTEST
</div>
Nothing happens. Can anyone please explain where I am going wrong, I see all the JS and CSS loaded and on the page.
Thank you,
Daniel
Typically, Fancybox is initialized on an anchor tag which points to a div element or a link housing the content to be shown on the Fancybox:
HTML:
Click here to launch Fancybox
<div style="display:none">
<div id="single_1">
Content goes here
</div>
</div>
Javascript:
$(function(){
$('a#fancybox').fancybox({
// Fancybox options here
})
.trigger('click'); //Optional - if you wish to trigger the Fancybox after initialization
});
Try using,
$(document).ready(function() {
$("a #single_1").fancybox();
});
<a id="single_1" href="#">
TESTTESTEST
</a>
You've merely instantiated the plugin. You have to trigger it now.
So you can add any DOM element and watch for an event then trigger the plugin.
Click me
The JS
$('fancyme').on("click", function() {
$.fancybox('#single_1');
});
OR
You can trigger on page load
$(function(){
$.fancybox('#single_1');
});

preventDefault() on an <a> tag

I have some HTML and jQuery that slides a div up and down to show or hide` it when a link is clicked:
<ul class="product-info">
<li>
YOU CLICK THIS TO SHOW/HIDE
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
}
My question is: How do I use preventDefault() to stop the link acting as a link and adding "#" to the end of my URL & jumping to the top of the page?
I can't figure out the right syntax, I just keep getting an error saying
preventDefault() is not a function.
Try something like:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
event.preventDefault();
$(this).next('div').slideToggle(200);
});
Here is the page about that in the jQuery documentation
Set the href attribute as href="javascript:;"
<ul class="product-info">
<li>
YOU CLICK THIS TO SHOW/HIDE
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
It's suggested that you do not use return false, as 3 things occur as a result:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
So in this type of situation, you should really only use event.preventDefault();
Archive of article - jQuery Events: Stop (Mis)Using Return False
1 - Easy way:
Click Me
2 - using void(0):
Click Me
3 - Using preventDefault():
Click Me
4 - Yet another way of doing this in Javascript using inline onclick, IIFE, event and preventDefault():
Click Me
Alternatively, you could just return false from the click event:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
+ return false;
});
Which would stop the A-Href being triggered.
Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)
This is a non-JQuery solution I just tested and it works.
<html lang="en">
<head>
<script type="text/javascript">
addEventListener("load",function(){
var links= document.getElementsByTagName("a");
for (var i=0;i<links.length;i++){
links[i].addEventListener("click",function(e){
alert("NOPE!, I won't take you there haha");
//prevent event action
e.preventDefault();
})
}
});
</script>
</head>
<body>
<div>
<ul>
<li>Google</li>
<li>Facebook</li>
<p id="p1">Paragraph</p>
</ul>
</div>
<p>By Jefrey Bulla</p>
</body>
</html>
<ul class="product-info">
<li>
YOU CLICK THIS TO SHOW/HIDE
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
Use
javascript:void(0);
After several operations, when the page should finally go to <a href"..."> link you can do the following:
jQuery("a").click(function(e){
var self = jQuery(this);
var href = self.attr('href');
e.preventDefault();
// needed operations
window.location = href;
});
Why not just do it in css?
Take out the 'href' attribute in your anchor tag
<ul class="product-info">
<li>
<a>YOU CLICK THIS TO SHOW/HIDE</a>
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
In your css,
a{
cursor: pointer;
}
If stopping the propagation of the event doesn't bother you, just use
return false;
at the end of your handler. In jQuery it prevents the default behaviour and it stop the event bubbling.
You can make use of return false; from the event call to stop the event propagation, it acts like an event.preventDefault(); negating it. Or you can use javascript:void(0) in href attribute to evaluate the given expression and then return undefined to the element.
Returning the event when it's called:
...
Void case:
...
You can see more about in: What's the effect of adding void(0) for href and 'return false' on click event listener of anchor tag?
In Javascript you can use it
window.event.preventDefault();
It works in my case. write the above line into your function.

Categories

Resources