jQuery - How check if any link was clicked in a specific DIV? - javascript

In HTML code my page contains:
<div id="main_menu">
Link1
Link2
</div>
<div id="second_menu">
Link info
My profile
</div>
<div id="menu_oustide">Link1</div>
In jQuery if I want to check if the user clicked any link in page I use this code:
$('a').click(function() {
// do something
});
How can I start a function if the user clicked only on links in specific div? I would like to have a function that starts if a user clicked any link only in div ID named "main_menu" AND "second_menu", but not in "menu_outside".

Depending on what exactly you want to do, you can bind the event handler to those links only, using the descendant [docs] and multiple [docs] selectors:
$('#main_menu a, #second_menu a').click(function() {
// link inside #main_menu or #second_menu
});
If you don't want to perform the same action for both, you have to bind the event handler individually.
You could also check dynamically whether the link is a descendant of any of these element, with closest [docs]:
$('a').click(function() {
if($(this).closest("#main_menu").length) {
// inside #main_menu
}
if($(this).closest("#second_menu").length) {
// inside #second_menu
}
//...
});
But that introduces an additional overhead.

use this to select the div and ahref you want.
$('#second_menu a').click(function(){
// This will select the a href's only in the second menu.
// basically, in div id "#second_menu" select all "a" elements.
});

Related

Execute function in this same element

I'm new here, and in Jquery ...
I am using Wordpress to create a website and I have a Jquery function for opening cards, these cards have a plus button, and clicking that button opens a description of the card ...
So far so ok, but all the cards have the same classes (on the button, and the description) and pulling it on the page I need to use them by clicking on one of the buttons it opens all the descriptions of the other cards ... can i make it open only the card description of the button i clicked?
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(this).ready(function(){
$(".abrir-btn").click(function(){
$(".conteudo-div").show(200);
$(".abrir-btn").hide();
$(".fechar-btn").show();
$(".listing-nucleados").css("background-color", "#FFE500");
$(".listing-nucleados").css("border-color", "#fff");
});
$(".fechar-btn").click(function(){
$(".conteudo-div").hide(200);
$(".abrir-btn").show();
$(".fechar-btn").hide();
$(".listing-nucleados").css("background-color", "#fff");
$(".listing-nucleados").css("border-color", "#EBEBEB");
});
});
</script>
Assuming, the buttons as well as the .listing-lucleados are both wrapped inside a parent element (let's call it .my-parent here). You can do the following:
$(this).ready(function(){
$(".abrir-btn").click(function(){
$(this).hide();
var parent = $(this).parents('.my-parent');
parent.find(".conteudo-div").show(200);
parent.find(".fechar-btn").show();
parent.find(".listing-nucleados").css("background-color", "#FFE500").css("border-color", "#fff");
});
$(".fechar-btn").click(function(){
$(this).hide();
var parent = $(this).parents('.my-parent');
parent.find(".conteudo-div").hide(200);
parent.find(".abrir-btn").show();
parent.find(".listing-nucleados").css("background-color", "#fff").css("border-color", "#EBEBEB");
});
});
Basically, what this does is going up the DOM tree to the parent element wrapping the show/hide buttons, as well as the list to show/hide. Then, from the parent element, find its descendants (I'm not saying direct children, because I do not know that much about your HTML structure) and apply the operation only to elements of this class inside the parent element.
In the function performed after clicking the button find a common ancestor of both elements - the button and the description - using closest().
Having an ancestor, find in it elements with the class .abrir-btn, .fechar-btn or .conteudo-div.
Example HTML:
<div class="content-outer">
<!-- the order inside is not important -->
<button class="abrir-btn" >show</button>
<button class="fechar-btn" >hide</button>
<div class="conteudo-div">...</div>
</div>
$(this).ready(function(){
$(".abrir-btn").click(function( event ){
var parent = $(event.target).closest(".content-outer");
if ( !parent.length )
return;
parent.find(".conteudo-div").show(200);
parent.find(".abrir-btn").hide();
parent.find(".fechar-btn").show();
parent.find(".listing-nucleados").css("background-color", "#FFE500").css("border-color", "#fff");
});
});

jQuery .on('click') firing multiple times when used with :not() selector

Good morning,
I have a set of boxes on a page that are presented as a list, and within these boxes there might be some links that can be clicked. I want the links within the boxes to work as normal (i.e. bubble up and either perform the default action or then be handled by event handlers further up the DOM), but if the box is clicked anywhere else then it should be caught by a particular event handler attached to the "list" containing all the boxes.
Simple html representation
<div class="boxlist">
<div class="box" data-boxid="1">
Some text, and possibly a link and another link, and perhaps even a third link.
</div>
<div class="box" data-boxid="2">
Some more text, this time without a link.
</div>
</div>
The javascript that I thought should work.
$(function () {
$('.boxlist').on('click', '.box :not(a)', function (e) {
var boxid= $(this).closest('.box').data('boxid');
console.log('open: ' + boxid);
});
});
My expectation was that the above javascript should handle all clicks that did not originate from tags. However, for some reason when the box is clicked (either the box itself, or an tag, doesn't matter), it fires this event X times, where X is the total number of tags within the list of boxes.
So I have two questions:
1. What am I doing wrong with the :not() selector.
2. Is there a better way to handle this scenario?
Thank you for helping!
linkUsing jQuery :not selector actually is very slow ex:http://jsperf.com/not-vs-notdasdsad/4 and it's way better to just use event delegation. So in this case you want to keep track of every click on the .boxlist but check the node type to see if its an anchor or not. This is an example.
$(function () {
$('.boxlist').on('click', function(ev){
if(ev.target.tagName != "A"){
// handle box click code
console.log('box click');
return false;
}
// Otherwise allow event to bubble through.
});
});
and here is a jsfiddle example
http://jsfiddle.net/drXmA/
Also their are a few reasons your code doesn't work
.box :not(a)
should be
.box:not(a)
and the reason this also does not work is because .box is not an anchor tag it has children elements that are anchor tags it will never find an anchor tag named .box if their is one the callback would not execute. Changing the .box to an anchor tag will make it so the code doesn't execute because .box is an anchor and it is only running when .box:not(a)
I guess you want something like this:
$('.boxlist').on('click', '.box:not(a)', function (e) {
var boxid = $(this).closest('.box').data('boxid');
console.log('open: ' + boxid);
}).on('click', '.box a', function (e) {
e.preventDefault().stopPropagation();
});
DEMO FIDDLE
I think better to stop the default behavior and stop the event bubbling to its parent. .on() chain to the .box items excluding <a> from it and stop the default behavior and event bubble with e.preventDefault().stopPropagation();

use selectors in variable jquery

i have to made functionality like this on click of a link it will show the product details in a popup like box
this is using a big jquery code i didn't understand
and here is my jsfiddle
i am trying to give some links same class with different #tags to show the div
and i want that when i click on link it resolves the href value of the same and show the corresponding result but it didnt works
can somebody suggest the right way
here is my JS
$(".show").click(function() {
var link = $('this').attr('href');
$(link).show();
});
and html
a
b
c
i want to show #popup on anchor click
full code on fiddle and i want this functionality
You should call $(this), not $('this')
$(this) wraps the object referred to by this inside a jQuery object,
$('this') will traverse all of your document looking for html nodes tagged this (much like $('div') will look for html nodes tagged div); since there isn't any, it will select an empty list of nodes.
Working fiddle : http://jsfiddle.net/Hg4zp/3/
( there also was a typo, calling .hide(") instead of .hide() )
Try this way:
$(".show").click(function (e) { //<-----pass the event here
e.preventDefault(); //<--------------stop the default behavior of the link
var link = $(this).attr('href'); //<-remove the quotes $(this)
$(link).show();
});
$(".close").click(function () {
$(this).closest("div.popupbox").hide(); //<----use .hide(); not .hide(");
});
You should use preventDefault() in these cases to stop the jump which take place when a link get clicked.

How to targeting Specific Elements with Common Classes, using jQuery Toggle?

I'm creating a drop down menu that will be reused many times on a single page.
The following code works great when there's only one drop down menu. But when there are multiple drop downs, clicking a single .dropdown will result in all the .dd_menu's on the page being revealed.
JS:
$(document).ready(function() {
$('.dropdown').click(function(){
$('.dd_menu').toggle();
});
});
HTML:
<div class="dropdown">
<a class="mini_button" href="#">Actions</a>
<div class="dd_menu">
Link
Link
Link
</div>
</div>
Is there some what to target only the .dd_menu that is inside the particular .downdown which was clicked?
Limit the selector to the .dd_menu that is a child of the current clicked .dropdown div:
$(document).ready(function() {
$('.dropdown').click(function(){
$('.dd_menu', this).toggle(); // <========== used this as a context.
});
});
jQuery( selector [, context] ):
selector A string containing a selector expression
context A DOM Element, Document, or jQuery to use as context
docs
You can also use the find function: $(this).find('.dd_menu') but it exactly the same. the context selector is calling the find function.
You could try:
$(this).children('.dd_menu').toggle();
$(document).ready(function() {
$('.dropdown').on('click', 'a', function(){
$('.dd_menu:eq('+$(this).parent().index()+')').toggle();
});
});​

Select next element of a given class

I want to hide and show some form in my page.
For each form theres a link, and i want that, when i click on this link,
it hide and show the nearest form of the link.
My code looks like this :
$$('.flagLink').each(function(s){
$(s).observe('click', function(event) {
// here i want to hide and show the nearest form
});
});
I've tried this :
$$('.flagLink').each(function(s){
$(s).observe('click', function(event) {
$(s).next('form').toggle();
});
});
It works but, i would like to be more precise like :
$$('.flagLink').each(function(s){
$(s).observe('click', function(event) {
$(s).next('.flagForm').toggle();
});
});
but the .flagForm selector doesnt work.
My code looks like this :
flag
First I hide all the form in the page :
$$('.flagForm').each(function(s){
$(s).hide();
});
Then i add the onclick event on them:
$$('.flagLink').each(function(s){
$(s).observe('click', function(event) {
$(s).next('.flagForm').toggle();
});
});
But with the .flagForm selector, it does not work
To avoid hazardous DOM traversal, I recommend using element ids to bind a form to its link, like so:
<form id="myform1">...</form>
...
<a id="link_myform1" class="flagLink" href="#">...</a>
Then you can match the id of your A element against a regexp /link_(.*)/ to get the id of your form:
$$('.flagLink').invoke('observe', 'click', function(event) {
if(event.element().id.match(/link_(.*)/)) $(RegExp.$1).toggle();
});
If you can't use this solution, then you have to be more specific about what you mean by "nearest". If the link and the form always have a common ancestor, then you can use a css selector to find the form wherever it is. Say the link and the form always have a common ancestor that is the grand-parent of the link, you can do:
$$('.flagLink').invoke('observe', 'click', function(event) {
var form = event.element().up(2).select('form').first();
if(form) form.toggle();
});

Categories

Resources