jQuery click method on nested classes - javascript

Starting from the snippet:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<ul>
<li><a class="parentClass" href="#">Parent</a></li>
</ul>
<script>
jQuery(document).ready(function($){
$('.parentClass').append("<span class='childClass'> || Child</span>");
$('.parentClass').click(function(e){
alert('parent');
});
$('.childClass').click(function(e){
//$('.childClass').removeClass('parentClass');
alert('child');
});
});
</script>
</body>
</html>
If I click on "Parent" I can view the alert('parent') only, but if I click on "Child" I will fire not only alert('child') but also alert('parent').
I tried to insert $('.childClass').removeClass('parentClass'); but it doesn't work. I can't figure out how to avoid to launch the parent from child, without modify the nested classes inside the anchor...is it possible?

Events bubble, you can stop the propagation
jQuery(document).ready(function($) {
$('.parentClass').append("<span class='childClass'> || Child</span>");
$('.parentClass').click(function(e) {
alert('parent');
});
$('.childClass').click(function(e) {
e.stopPropagation();
alert('child');
});
});
FIDDLE
or make sure the parent was actually the target
jQuery(document).ready(function($) {
$('.parentClass').append("<span class='childClass'> || Child</span>");
$('.parentClass').click(function(e) {
if ( this === e.target ) {
alert('parent');
}
});
$('.childClass').click(function() {
alert('child');
});
});
FIDDLE

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<ul>
<li><a class="parentClass" href="#">Parent</a></li>
</ul>
<script>
jQuery(document).ready(function($){
$('.parentClass').append("<span class='childClass'> || Child</span>");
$('.parentClass').click(function(e){
alert('parent');
});
$('.childClass').click(function(e){
//$('.childClass').removeClass('parentClass');
alert('child');
e.stopPropagation();
});
});
</script>
</body>
</html>
All you need is to use .stopPropagation()

You need to use event.stopPropagation():
$('.childClass').click(function(e){
e.stopPropagation();
alert('child');
});

Related

Can't select elements with jQuery

I want to prevent a link from taking the user to another page.
When I try to select elements with getElementById("id"), it works fine. When I try to select by using $("#id"), however, it doesn't work. To clarify, this works:
https://jsfiddle.net/1nwaptL9/
but this doesn't work: https://jsfiddle.net/7vkepm9e/1/
I realise both of these fiddles do actually work, but when I load the HTML files in Chrome, the one with the jQuery selection doesn't work. Since the source code I've included below works fine in JSFiddle, but not in Chrome, I suspect I've done something wrong, but JSFiddle doesn't process links or something like that. Any help would be appreciated!
Source code that doesn't work:
<html>
<body>
<a id="preventlink" href="http://youtube.com"> click here </a>
<script src="js/jquery-1.11.3.min.js"> </script>
</body>
</html>
<script>
var link=$("#preventlink");
link.addEventListener("click", function(e) {
e.preventDefault()}, false)
</script>
jQuery creates a jQuery instance, if you want the actual DOM element, you can do the following:
var link = $("#preventlink")[0];
Or, just keep using jQuery to add events:
$("#preventlink")
.click(function (e) {
e.preventDefault();
});
Getting the element from the jQuery instance:
var link = $("#preventlink")[0];
link.addEventListener("click", function(e) {
e.preventDefault()
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="preventlink" href="http://youtube.com"> click here </a>
Sticking with just jQuery:
$("#preventlink").click(function(e) {
e.preventDefault()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="preventlink" href="http://youtube.com"> click here </a>
See jQuery's doc on the subject
This is because addEventListener is a javascript function. It's not defined for jquery. For jquery you can use bind function. Below is the sample code
$(document).ready(function() {
var link=$("#preventlink");
link.bind('click', function(e){
e.preventDefault();})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<body>
<a id="preventlink" href="http://youtube.com"> click here </a>
</body>
</html>
You are mixing jQuery with vanilla JS:
$("#id") -- jQuery
document.getElementById("id") -- Vanilla JS
Try to use either one of them.
jQuery:
$("#preventlink").on("click", function(e) {
e.preventDefault()
})
Vanilla JS:
var link=document.getElementById("preventlink");
link.addEventListener("click", function(e) {
e.preventDefault()}, false)
Here is a more jQuery way of doing what you are looking for
var $link = $("#preventlink");
$link.on("click", function(e) {
e.preventDefault();
alert("link clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<a id="preventlink" href="http://youtube.com"> click here </a>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</body>
</html>
Try this:
$("#preventlink").on('click', function (e)
{
e.preventDefault ();
});

jQuery - div inside div, how to run only 1 click event when inside has been clicked

I have a div inside div. If the inside div has been clicked (closeme div), I dont want to run the other div's (container div) click event. How can I do that ?
html
<div id="container">
content
<div id="closeme"></div>
</div>
js
$(document).on('click', '[id="container"]' ,function(){
alert("I am clicked");
}
$(document).on('click', '[id="closeme"]' ,function(){
alert("I am clicked");
}
$(document).on('click', '[id="container"]', function(e) {
e.stopPropagation();
alert("I am container");
})
$(document).on('click', '[id="closeme"]', function(e) {
e.stopPropagation();
alert("I am closeme");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
content
<div id="closeme">qwe</div>
</div>
Use event.stopPropagation()
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Do a if to test if the target is #closeme
$(document).on('click', '[id="closeme"]', function(event) {
if ($(event.target).is('[id="closeme"]')) {
alert("coloseme clicked");
}
});
Like others have just mentioned. You have to stop the event propagation. Here is a full working example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="container">
content
<div id="closeme">Inner Div</div>
</div>
</body>
<script>
$(document).on('click', '[id="container"]', function(event) {
alert("container clicked");
});
$(document).on('click', '[id="closeme"]', function(event) {
event.stopPropagation();
alert("coloseme clicked");
});
</script>
</html>

Hover on Image not working Javascript / JQuery

I am working on website which uses Jquery and CSS3.
I have image and on hover i want to scale image. Hover works with CSS but i want it to via JQuery following code i have tried till now. Please help.
HTML
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" type="text/css" href="css/app.css" />
</head>
<body >
<img class="img-responsive" id ="thumbnail" src="my-image-src">
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$("#thumbnail").on({
mouseenter: function () {
$(this).addClass("scaleout");
},
mouseleave:function () {
$(this).removeClass("scaleout");
}
},'img');
});
</script>
</body>
</html>
CSS
.scaleout {
transform: scale(1, 0.80);
-ms-transform: scale(1, 0.80);
-webkit-transform: scale(1, 0.80);
}
I also tried hover() method instead of mouseenter and mouseleave in above script code
$(document).load(function(){
$('#thumbnail').hover(function(){
$(this).toggleClass('scaleout');
},
function(){
$(this).removeClass('scaleout');
});
});
Please help why hover not working.
fiddle
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" type="text/css" href="css/app.css" />
</head>
<body >
<img class="img-responsive" id ="thumbnail" src="my-image-src">
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$( "#thumbnailtest" ).hover(
function() {
$(this).addClass("scaleout");
}, function() {
$(this).removeClass("scaleout");
}
);
});
</script>
</body>
</html>
Remove 'img' from event handler,
Its work for me
<script>
$(document).ready(function(){
$("#thumbnail").on({
mouseenter: function () {
$(this).addClass("scaleout");
},
mouseleave:function () {
$(this).removeClass("scaleout");
}
});
});
</script>
I've created a fiddle that works using code pretty similar to your second solution (use document.ready and no need for the removeClass function). https://jsfiddle.net/L5bj38me/
<script>
$(document).ready(function(){
$('#thumbnail').hover(function(){
$(this).toggleClass('scaleout');
})
});
</script>
Update OP's issue is due to Angular see - Run jQuery code after AngularJS completes rendering HTML
There are many ways to do it, one solution is -
$(document).ready(function(){
$('#thumbnail').on('mouseenter', function (e) {
$(this).toggleClass('scaleout');
});
});
Here's another one -
$("#thumbnail").mouseenter(function (e) {
$(this).toggleClass('scaleout');
});
Few more -
$( "#thumbnail" )
.mouseover(function() {
$(this).toggleClass('scaleout');
})
.mouseout(function() {
$(this).toggleClass('scaleout');
});
Same output but with different approach -
$( "#thumbnail" )
.mouseenter(function() {
$(this).toggleClass('scaleout');
})
.mouseleave(function() {
$(this).toggleClass('scaleout');
});

Adding a click function to a image element

I am trying to add 2 simple click functions to 2 images and make them "active" when clicked, however for some reason the code is not working.
This is the link to the external file:
<head>
<link href="bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.leanModal.min.js"></script>
<script type="text/javascript" src="likeandshare.js"></script>
<link type="text/css" rel="stylesheet" href="blogformat.css" />
<script type="text/javascript" src="likeandshare.js"></script>
</head>
This is the html:
<div class="blog-header">
<h1>This heading should be center aligned and colored</h1>
<p>Italised date and Author entered here</p>
<div id="facebook-like-button">
<img src="images/facebook_like_button_big.jpeg">
</div>
<div id="facebook-share-button">
<img src="images/facebook-share.png">
</div>
</div>
This is the js code:
$(document).ready(main);
var like = function() {
$("#facebook-like-button").click(function() {
$(this).toggleClass("active");
});
};
I'm not sure why the div is not becoming active when clicked but I would also like to attach the function ONLY to the image, rather than the entire div.
Help :D
thanks.
As far as I'm aware, your code should be working. You must be incorrectly calling the ready function.
working example http://jsfiddle.net/2j0s1j8v/3/
All of these events fire back:
share = document.getElementById("facebook-share-button");
share.onclick = function(){
console.log("ONCLICK");
}
share.addEventListener("click", function(){ console.log("CLICK LISTENER"); } );
$("#facebook-share-button").click(function() {
console.log("JQUERY CLICK");
});
Check the console and look at the messages. All of them fire properly. f12 on chrome.
You can simply do this :
$(document).ready(function(){
$("#facebook-like-button").find('img').click(function() {
$(this).toggleClass("active");
});
});
first include jquery
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="likeandshare.js"></script>
</head>
second you create a like function and use main function .. you have a main function also or bad typo or what anyway in your case it should be
$(document).ready(like);
if you want to select an image inside the div just use > a >img
var like = function() {
$("#facebook-like-button > a > img").click(function() {
$(this).toggleClass("active");
});
};
https://jsfiddle.net/2j0s1j8v/4/
Like button
$("#facebook-like-button img").click(function () {
$(this).toggleClass("active");
});
Share button
$("#facebook-share-button img").click(function () {
$(this).toggleClass("active");
});
Here is a working example if I understand correctly what you wanted.
adds active class to the image on click.
EDIT: added share as well

Regarding Combining Two Small Javascript Codes

Basically the question is self explanitory. I can't figure out how to combine small snippets of javascript rather than having two separate files.
The two codes are :
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
});
$(function(){
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
Another question, is the first $(function() necessary?
Thanks for you help.
You can do this way:
Create a function and call it under it. Or, you do this:
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
Some notes:
Those two functions are different.
You don't need the two function starters, $(function(){}) twice.
You can make it like this:
$(function(){
$('.navbar li, .dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
if($(this).parents(".navbar").length > 0)//this is to figure out if we are working with LI inside .navbar or not.
$(this).addClass('active').siblings().removeClass('active');
else
$(this).removeClass('active')
}
});
});
Functions are almost equal, except that you need to detect if you are working with LI from .navbar or not to select corect removeClass code.
Also, in your code first $(function() is necessary. Otherwise code inside it could be started before document is loaded. But you may put both pieces of code inside one $(function()
Full working sample, this will make the first LI of first UL red, and remove the red from the second ul LI. Your two functions are now combined.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<title></title>
<style type="text/css">
.active {background-color:red}
ul.dropdown-menu>li.active {background-color:red}
</style>
</head>
<body>
</body>
<ul class="navbar">
<li>first</li>
<li>old</li>
<li>new</li>
<li>4</li>
</ul>
<ul class="dropdown-menu">
<li class="active">first</li>
<li>old</li>
<li>new</li>
<li>4</li>
</ul>
<script type="text/javascript">
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
</script>
</html>

Categories

Resources