jquery select single tag class onclick - javascript

seems a little trivial but am having a hard time solving it, i have a jquery function to select the class of a tag on click but the problem is that it selects every other tag underneath the tag clicked as well in structural order where as i only want the very first one
for example if i have
<div class="1">
<div class="2">
<div class="3">
<p class="4">Hello World</p>
</div>
</div>
</div>
and i clicked on the (p) tag that says hello world i would get an alert
saying 4 then 3 then 2 then 1
but like i said i only want the first one witch in this case is 4
here is my jquery code
$("*").dblclick(function(){
if(!$(this).hasClass("") && !$(this).hasClass("main")){
alert($(this).attr('class'));
}
});
i know the problem is happening because technically i am clicking all of the tags so it continus to loop trough but i still need a way to break it after the first class is selected or better yet is there a way to select only the topmost object

Just add return to the function like so:
$("*").dblclick(function(){
if(!$(this).hasClass("") && !$(this).hasClass("main")){
alert($(this).attr('class'));
return false;
}
});

I would pass in event to your click function, and after you've finished your logic, use event.stopPropagation(). This prevents the event from bubbling up to parent elements
$("*").dblclick(function(event){
if(!$(this).hasClass("") && !$(this).hasClass("main")){
alert($(this).attr('class'));
}
event.stopPropagation();
});

Run this example and look your console.
$("body > div").dblclick(function(){
console.log($(this).attr('class'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="1">
<div class="2">
<div class="3">
<p class="4">Hello World</p>
</div>
</div>
</div>

You should read about event bubbling and event propagation.
Here is function which does what you want:
$("*").dblclick(function(e){
if(!$(this).hasClass("") && !$(this).hasClass("main")){
alert($(this).attr('class'));
e.stopPropagation();
}
});
And here is working example:
https://jsfiddle.net/18sawk57/
Although it's not a good solution to attach event listening to all of the tags on the page. Much better solution is to add for example id or clickable class attribute for elements that should have event listening.
Here is another working example with better approach: https://jsfiddle.net/tr7aqask/
Here is another working example with bubbling disabled using jquery: https://jsfiddle.net/yc0481sm/

Related

Jquery hide and show a button

First off, I've read extensively by now into what seem to be recurrent questions about how to hide a div after a properly detecting a click, or event, outside the div; indeed this has influenced my javascript code. But I'm a newbie and it's not working so I hope you can help me out.
Second, the jfiddle - https://jsfiddle.net/u5uzexqk/ ... please note the button should show when the any section of the search bar or indeed button is clicked on; and not show when a click anywhere outside is detected.
Before the code, I would just like to point out I have also read into the e-propagation thing, however I don't think it's the absence of that which is the problem; if it is, my profuse apologies.
Perhaps owing to the fact I'm new to Javascript, I can't see how the suggested answer from another question helps; the Jfiddle on the most popular answer seems to do the opposite - remove the menu when the menu link is clicked again.
Html
<body>
<div id = "wrapper">
<form action="" class="search-form">
<div class="cell">
<input type="text" name="q">
</div>
<div class="cell button-holder">
<button type="submit" id="dropdownbutton">
<span>Search</span>
</button>
</div>
</form>
</div>
</body>
Javascript
$("#wrapper").onclick(function (e){
document.getElementById('#dropdownbutton').style.visibility = 'visible';
}
$(document).mouseup(function (e)
{
var container = $("#wrapper");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$("#dropdownbutton").hide();
}
});
});
You are mixing methods for hiding and showing. If you are going to use .hide() then use .show() when showing it.
With your code, the call to .hide() will set the style to display: none, but then your native Javascript technique to show the button (which also contains the pound symbol in the id i.e. document.getElementById('#dropdownbutton') - don't confuse it with jQuery's selector when calling document.getElementById()) just adds a style for visibility: visible. Those are different properties.
<button type="submit" id="dropdownbutton" style="display: none; visibility: visible;">
<span>Search</span>
</button>
Also, as was pointed out in comments, there is no jQuery method .onclick. Use .click(). Also, there is a missing closing parenthesis after the click handler for the wrapper button. So update it like this:
$("#wrapper").click(function(e) {
$("#dropdownbutton").show();
}); // <- add parenthesis (and optional semi-colon) to terminate the function call
And has already been mentioned, you should wait until the DOM is ready to access elements. With jQuery, use document.ready().
$(document).ready(function(readyEvent) {
//interact with DOM
//now that the DOM is ready
//e.g. fetch elements by id attribute, add event handlers, etc.
});
See these changes in action in the snippet below:
$(document).ready(function() {
$("#wrapper").click(function(e) {
//document.getElementById('dropdownbutton').style.visibility = 'visible';
$("#dropdownbutton").show();
});
$(document).mouseup(function(e) {
var container = $("#wrapper");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$("#dropdownbutton").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<form action="" class="search-form">
<div class="cell">
<input type="text" name="q">
</div>
<div class="cell button-holder">
<button type="submit" id="dropdownbutton">
<span>Search</span>
</button>
</div>
</form>
</div>
First let's point out some issues in your code:
There is no such function as onclick in jQuery. To attach a click event you either use: $(...).click(callback) or $(...).on("click", callback).
The oposite of show is not visibility = "visible". show uses the display property (show = display = "none") and its oposite is hide (display = ""). So use show and hide.
Since you are already using jQuery, why use document.getElementById, just $("#id") will do.
Instead of all those checks to see if the target is the wrapper or something inside the wrapper, just stop the propagation of the event inside the event listener of the wrapper so it will never reach the document.
You should wrap your code inside a load event- $() will do- To make sure that everything is loaded before starting doing anything.
$(function() {
$("#wrapper").click(function(e) {
$("#dropdownbutton").show();
e.stopPropagation(); // if the event occur inside the wrraper, prevent it from bubbling up to the document and fires the bellow function
});
$(document).click(function(e) { // if the click target is the #wrapper (or something inside it) this event will never reach the document because of the stop propagation inside the above listener. So if this is fired then the target is not the wrapper, therefore we should hide the button
$("#dropdownbutton").hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="wrapper">
<form action="" class="search-form">
<div class="cell">
<input type="text" name="q">
</div>
<div class="cell button-holder">
<button type="submit" id="dropdownbutton">
<span>Search</span>
</button>
</div>
</form>
</div>
</body>
I would do it like this:
$("document").ready(function(){
$("#dropdownbutton").hide();
$( "input[name=q]" ).on( "focus blur", function() {
if($(this).is( ":focus" ) ){
$("#dropdownbutton").show();
}else{
$("#dropdownbutton").hide();
}
});
});
Demo: http://codesheet.org/cs/wAnG3ofQ

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>

Find third parent from a parent-child in jquery

<div>
<div>
<div class="one">child of 1 st Div</div>
</div>
<div>
<div class="two'>child of 2 st Div</div>
</div>
<div>
<div class="three">child of 3 st Div</div>
</div>
</div>
Here what I want to do is on clicking the div with class="one" I want to change the content of the third div where class="three"
You have a typo error here : <div class="two'> it should be this : <div class="two">
For the script, there are many way to do it, here is one :
$(function(){
$('.one').click(function(){
$('.three').text('hey');
});
});
Live example
In jQuery, you can attach a click event handler to a jQuery object using the click method. You select an element using the global jQuery function (usually jQuery or $). To select an element with a specific class, prepend . to the class.
$('.one').click(function(event) {
// this function will be fired when the div with class `one` is clicked
var $three = $('.three');
// $three is now a jQuery object representing the div
// DOM element with the class `three`
// your code here
});
First of all in your code you should correct your code for class = "two". In order to select a div use jquery .on() event handler.
$('selector').on('click',callback());
Refer to the following code.
$('.one').on('click',function(){
$('.three').addClass('changeColor');
})
I have also created a jsFiddle: https://jsfiddle.net/58kng68a/

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

How to get a value from div without write some event (onclick,etc) using jquery

I have some question about how to get some value from some element like div,etc using jquery and without write onclick event or etc on the div where I want to get that value.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="test" title="test1">test</div>
<div id="test2" title="test2">test2</div>
<script>
function getVal(attr,value){
$("#show").text("this "+attr+" have value ="+value);
}
$(document).ready(function(){
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
});
</script>
<div id="show"></div>
</body>
</html>
Usually to get some value from div that i click, I add an onclick event on div like
<div id='test' onclick="getVal(test)" ></div>
and it will return "test". And the code that I write above nearly what I want, but the problem that I have is if I have a many div, how can I get the value from each div that I click just using jquery click function and I don't need to write
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
$("#test2").click(function(){
getVal("#test2",$("#test2").attr("title"));
});//and so on
here the code that I use to achieve what I want, using onclick event that I put on div:
<script type="text/javascript">
function overlay(rel){
var value = rel;
$(document).ready(function(){
$(".img"+value).click(function(){
$(".overlay-bg"+value).fadeIn();
});
$(".close"+value).click(function(){
$(".overlay-bg"+value).fadeOut();
})
});
}
</script>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-a.jpg" class="img1" onclick="overlay(1)" title="photo1" alt="photo1"/>
</div>
<div id="overlay-bg" class="overlay-bg1">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/a.jpg"/>
<span>photo1</span>
<span style="font-size:0.8em;"><p>photo a</p></span>
<div id="close" class="close1"></div>
</div>
</div>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-b.jpg" class="img2" onclick="overlay(2)" title="photo2" alt="photo2"/>
</div>
<div id="overlay-bg" class="overlay-bg2">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/b.jpg"/>
<span>photo2</span>
<span style="font-size:0.8em;"><p>photo b</p></span>
<div id="close" class="close2"></div>
</div>
</div>
I'm really want to know how to resolve my problem.
Give the elements you want to attach the click event handler to the same class. Then use the class selector [docs] to select all of them:
$('.sharedClass').click(function() {
getVal(this.id, $(this).attr("title"));
});
jQuery will bind the event handler to each of the selected elements.
There are many ways to select elements [docs], selection by ID or class are just two of them. You might also find the jQuery tutorial useful to get a better idea of how jQuery works.
you can use the this keyword within the handler function, and it will point to the element that was clicked
Here's the correct way to do it.
Put a class name to your target div e.g.
<div id="test" class="clickable" title="test">test</div>
<div id="test2" class="clickable" title="test">test</div>
...
...
Then create a jQuery event with selected class
$('.clickable').click(function(){ ... });
<div id="test">harsh</div>
<script>
alert(document.getElementById('test').innerHTML);
</script>
If you want to call this function with the click of every div, use :
$("div").click(function(){
getVal($(this),$(this).attr("title"));
});
If you want to call the function for a set of divs, but not all, give those divs a class name as suggested by #Felix Kling.
Check out the jQuery Selectors to get a better idea.
Not sure what you're trying to achieve.
If you have multiple values how do you want to store them?
If you have an array that you wanted to populate you can use the each() function on a JQuery selector to traverse all elements selected.
Like so:
var values = new Array();
$(document).ready(function(){
$('#test1, #test2').each(function(){
values.push($(this).html());
});
});
You could also store the values in an associative way to make retrieval a bit easier if you didn't want to iterate through an array. For example you could use the value of the 'title' attribute as the key in the array.
Replace the values.push() line with this line of code:
values[$(this).attr('title')] = $(this).html();

Categories

Resources