$(document).on('click', selector, function() ) combined with :not - javascript

I've got several list items, when I click on the item I want the browser to redirect to ".title > a" link (href). But I don't want any event on the "notThis" selector.
see the example
http://jsfiddle.net/VTGwV/29/
<div class="item">
<div class="title">
jsfiddle.net
</div>
<div> djføljdsaføljdsf a</div>
<div> djføljdsaføljdsf a</div>
<div> djføljdsaføljdsf a</div>
<div class="notThis">
link1
link2
</div>
​
script
​$(document).on('click', '.item', function(event) {
window.location.href = $(event.currentTarget).find('.title > a').attr('href');
});​
I've tried :not('.notThis') without any luck.
Changes
Thanks for all the answers, but I found another problem. If I have a event handler on the whole item , I can't manage to click on the link in "notThis" selector, because it returns only "false". Isn't there a way to use .not / :not combined with $(document).on('click', -------)

You can test whether the click event originated from within the .notThis element (or the element itself):​
$(document).on('click', '.item', function(event) {
if($(event.target).closest('.notThis').length > 0) {
return false; // if you want to ignore the click completely
// return; // else
}
window.location.href = $(event.currentTarget).find('.title > a').attr('href');
});​
I also think you can use this instead of event.currentTarget.

Your syntax is wrong, just use the selector like this:
Example
$("div.item > div:not(.notThis)").click(function(){
window.location.href = $(this).find('.title > a').attr('href');
});

http://jsfiddle.net/Lcg49/4/
var clickable = $('.item').find('div').not('.notThis');
$(clickable).on('click', function(event) {
alert($(this).parent().find('.title a').attr('href'));
});

Related

How to set $(this) as the clicked element

In the following code:
// submit an item
$(document).on("click", ".match-item", function(event) {
// how to set $(this) == $('.match-item') clicked?
});
I'm looking to retrieve $(this) as the clicked item and not the document itself. How would I do this?
This is more of clarification rather than answer.
this is already referring to the currently clicked element.
$(document).on("click", ".match-item", function(event) {
console.log($(this).attr('class'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
Parent
<div class="match-item">----Click Me</div>
</div>
How about
$('.match-item').click(function() {
//your code with $(this) here
});
I am pretty sure $(this) will refer to the element with class match-item

Styled Select Fields with jquery and HTML Listelements

i have a little problem with my styled Selectfield. I used for this unordered list elemnts (UL / LI) and a H3.
The problem is to close the "Selectfield" by clicking anywhere on the page.
When i bind a click event to the "document", then don't open the SelectField with the current jQuery code.
I have hidden the UL Element by using CSS (display:none).
To open the Select Fields is not the problem. But only without the $(document).bind('click') [...] code.
I hope anyone have a resolution for my.
Thanks.
And here my HTML Code:
<div class="select_container">
<h3 class="reset">Select Items</h3>
<ul class="select_elements">
<li>Select Item 01</li>
<li>Select Item 02</li>
<li>Select Item 03</li>
</ul>
</div>
And here the jQuery Code:
$(document).ready(function(){
var selectFields = {
init: function(){
$('.select_container').on('click',function(){
$(this).find('ul.select_elements').toggle();
$(this).find('ul.select_elements').toggleClass('active');
});
$(document).bind('click',function(){
if( $('.select_elements').is(':visible')){
$('.select_elements.active').hide();
}
else if( $('.select_elements').is(':hidden')){
console.log('visible false ...');
}
});
}
};
$(selectFields.init);
});
You need to use .stopPropagation in $('.select_container').on('click') function to prevent triggiring $(document).on('click')
You need to use toggleClass in $(document).on('click') too
$('.select_container').on('click',function(e){
$(this).find('ul.select_elements').toggle();
$(this).find('ul.select_elements').toggleClass('active');
e.stopPropagation();
});
$(document).on('click',function(){
if( $('.select_elements').is(':visible')){
$('.active').hide();
$('.select_elements').toggleClass('active');
}
else {
console.log('visible false ...');
}
});
FIDDLE
In jquery and javascript an event bubbles up so you have to use e.stopPropagation() on your container click.
check theese pages linki1 or link2 and a possible solution to your problem could be
<script type="text/javascript">
$(document).ready(function(){
var selectFields = {
init: function(){
$(document).bind('click',function(e){
if( !$('ul').hasClass('active')){
$('ul').hide()
$(this).find('ul.select_elements').toggleClass('active');
}
});
$('.select_container').on('click',function(e){
e.stopPropagation()
if( $('ul').hasClass('active')){
$('ul').show()
}else{ $('ul').hide() }
$(this).find('ul.select_elements').toggleClass('active');
});
}
};
$(selectFields.init);
})
</script>
With stopPropagation prevent the event from bubbling and being caught by the document when you click on the list
in some cases you can also use stopImmediatePropagation, for understand differences between stopPropagation and stopImmediatePropagation check this post Post
The only drawback to similar code and to and Batu Zet code, is that If you want the items in the list can be clicked without disappearing, you have to add another stopPropagation on ul tag
Tis is the final Fiddle

How to toggle the link in my case?

I am trying to toggle a link texts and content when user clicks the link.
I have something like
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
})
When user click the link, the link text will become isClicked and the items html will be replaced with a image. However, if user clicks again, I want to see the link text changes back to click me and the items will hide the image and display the title and p tag contents again.
I am not sure how to accomplish this. Can anyone help me about it? Thanks a lot!
You can add a dummy class to the link and work with that condition
//Have a dummy class added to the link and toggle it on click
$('#link').on('click', function(e){
e.preventDefault();
var $this = $(this),
$textDiv = $('#items'),
$imageDiv = $('#image')
if($this.hasClass('clicked')) {
// remove the class
$this.removeClass('clicked');
// change the text
$this.text('click me');
// Hide image
$imageDiv.addClass('hide');
// show text
$textDiv.removeClass('hide');
} else {
// remove the class
$this.addClass('clicked');
// change the text
$this.text('isClicked');
// Show image
$imageDiv.removeClass('hide');
// Hide text
$textDiv.addClass('hide');
}
});
Check Fiddle
You can also chain the methods applied on the same element.
$('#link').on('click', function(e){
e.preventDefault();
if ($(this).text() == "isClicked") {
$(this).text("click me");
.. etc
} else {
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
}
});
Like I said in my comment, use a condition like this. Simple and effective.
One way you could do it:
$('#link')
// Set data attribute to hold original text
.data('primeText', $('#link').text())
// set click event using jQuery1.73+
.on('click', function(e) {
e.preventDefault(); // prevents going to link, not needed if you set link href to "javascript:void(0)"
// begin setting text, within is a inline-if statement testing current text against prime text
$(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});
Another way, if you were working with more than one, like using a class name instead of ID:
$('.link')
// jQuery's .each method allows you to do things to each element in an object group
.each(function(i) { $(this).data('primeText', $(this).text()); })
// again, calling click method
.on('click', function(e) {
$(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});
Examples
What about using a CSS approach?
Your HTML would stay the same:
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
But we can use .toggleClass() here to make our lives easier
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').toggleClass('display-image');
})
The CSS would look like:
#items.display-image > h1,
#items.display-image > p,
{
visibility:hidden;
}
#items.display-image{
background-image:url("/images/image.png");
}
This way, you don't have to worry about removing things and .toggleClass handles their visibility.
You might have to do additional styling to get the image to work properly, or you may consider adding another element to contain the image and you can just set its visibility or display property
Try something like this:
HTML:
<a id='link' href='#'>click me</a>
<div id='items'>
<h1 class="text-item">title here</h1>
<p class="text-item">texts here...</p>
<img src="images/images.png" alt="Image" />
</div>
CSS:
img {
display: none;
}
JavaScript:
$('#link').off().on('click', function(e) {
e.preventDefault();
if($('#items > img').is(':visible')) {
$(this).text('click me');
$('#items > img').hide();
$('#items > .text-item').show();
} else {
$(this).text('isClicked');
$('#items > .text-item').hide();
$('#items > img').show();
}
});
Fiddle
You can try to store the value in a var and then toggle with on off in functions themselfs;
var initialState = $('#items').html(),
functionBla(e) {
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
$('#link').off('click').on('click', functionCla);
},
functionCla(e) {
e.preventDefault();
$(this).text('click');
$('#items').html(initialState);
$('#link').off('click').on('click', functionBla);
};
$('#link').on('click', functionBla);
You can do it like,
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').children().toggle();
var img=$('#items img');
if(img.length>0){
img.remove();
}
else{
$('#items').append("<img src='images/image.png' />");
$(this).text('Click me');
}
})

Hide/show DIVs in JS no longer working - potential conflict btw scripts

I used this tutorial to hid/show DIVs. Unfortunately for some reason it's no longer working (I modified a few things in my code in the meantime)... Do you see where the issue come from? jsfiddle: http://jsfiddle.net/Grek/C8B8g/
I think there's probably a conflict btw the 2 scripts below:
function showonlyone(thechosenone) {
$('.textzone').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200);
}
else {
$(this).hide(200);
}
});
}
$('.activity-title a').click(function(){
$('.textzone').fadeOut(2000);
var region = $(this).attr('data-region');
$('#' + region).fadeIn(2000);
})​
You have a few problems going on. You're missing data-source on your <a> elements. Their "region-source" is hidden inside of the href with some function. I removed that put it into data-source and now it all works fine.
You want to do something like this:
$('.activity-title a').click(function(){
var region = $(this).attr('data-region');
$('.textzone:visible').fadeOut(2000, function () {
$('#' + region).fadeIn(2000);
});
return false; // stops href from happening
})​;
// HTML Structured like so:
<div class="source-title-box"><span class="activity-title">
Our region</span>
</div>
jsFiddle DEMO
I assume from your markup in the jsFiddle that for every link (.activity-title a), there is a .textzone. I removed the onclick event from these anchors. This way The first link corresponds with the first .textzone:
<div id="source-container">
<div id="source-region" class="textzone">
<p><span class="activity-title">Interacting with the nature</span></p>
<p>blablabla</p>
</div>
<div id="source-oursource" class="textzone">
<p><span class="activity-title">Pure, pristine, and sustainable source</span></p>
<p>blablabla</p>
</div>
<div class="source-title-box"><span class="activity-title">Our region</span></div>
<div class="source-title-box"><span class="activity-title">Our source</span></div>
</div>​
Then with the script I simply use the index of the link which is clicked to determine the appropriate .textzone to show:
var textZones = $(".textzone");
var anchors = $('.activity-title a').click(function(e){
e.preventDefault();
var index = anchors.index(this);
textZones.filter(":visible").fadeOut(2000, null, function() {
textZones.eq(index).fadeIn(2000);
});
})​

jQuery making selection

I have a nested div like this
<div id="one">
<div id="two">
id two goes here
</div>
<div id="three">
id three goes here
</div>
<div id="four">
id four goes here
</div>
</div>
Now i want to handle click and doubleclick events on all divs except in div#four,
like this
$('#one').live('dblclick', function() {
my javascript code goes here
});
('#one').live('click', function() {
my javascript code goes here
});
How can i use the above script and exclude the last nested div #four.
Thanks
Like this:
$('#one, #one > div').not('#four').delegate('dblclick, click', function(){
// my javascript code goes here
});
EDIT: Based on further clarification, try this:
$('#one').bind('click dblclick', function( event ) {
var id = event.target.id;
if(id == "one" || id == "two" || id == "three") {
if(event.type == "click") {
// code for click event
} else {
// code for double click event
}
}
});​
EDIT: Based on our conversation under another answer, it seems like you want the #one element to be clickable, but none of its child elements. If that is right, try this:
$('#one').click(function() {
// code to run when `one` is clicked.
}).children().click(function( event ) {
event.stopPropagation();
});
Now if there's any text in #one, the code for that element will fire, but it will not fire when you click any children of #one.
Let me know if that was what you wanted.
EDIT:
If you are saying that you will have a dynamic number of elements inside #one, and the last one will not get the event, then do this:
$('#one').delegate('div:not(:last-child)', 'click dblclick', function( event ) {
if(event.type == 'click') {
// do something for the click event
} else {
// do something for the double click event
}
});​
Note that this assumes there will not be nested divs. Results may be unexpected if there are. Also, the #one element doesn't fire events. Only its children.
Original answer:
$('#one,#two,#three').bind('click', function(){
// code for click event
})
.bind('dblclick', function() {
// code for double click event
});
Or replace .bind with .live if you really need it.
I would use an additional class:
HTML:
<div id="one">
<div id="two" class="clickable">
id two goes here
</div>
<div id="three" class="clickable">
id three goes here
</div>
<div id="four">
id four goes here
</div>
</div>
JS:
('.clickable').live('click', function() {
});
Use not method, more on this here: How can I exclude these elements from a jQuery selection?
You must use $('#one') instead $('.one') aren't you?
$("div:not(#four)")
or
$("#one :not(#four)")
Will select any div that does not have the id="four" set. Basically the :not is what you are looking for. Anything in the :not parenthesis is negated for selection purposes.
http://api.jquery.com/not-selector/
An alternative is to attach a single click/double click handler to the parent which means no need for .live or anything, and in the handler ensure that you are receiving a click from an acceptable child with $(event.target).is(":not(#id)")
$("#one").click(function(event) {
if (this != event.target && $(event.target).is(':not(#four)')) {
// do work on event.target
}
});
// ...

Categories