jquery Trigger delegate event for nth element onload - javascript

In my page i have 10 images all are have the same class "select-option"
My html is
<div class="select-option swatch-wrapper selected" data-name="A Very Scary Monster" data-value="a-very-scary-monster">
<a href="#" style="width:120px;height:120px;" title="" class="swatch-anchor">
<img src="image ur1" alt="" class="" width="120" height="120"></a></div>
Similarly i have 10 images.
function init_swatches() {
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
}
I want to preselect the 3rd image. Thew selected image has the class 'selected', others are not. How do i trigger this for 3rd or 4th element on load. How to manually trigger this delegate event for nth element.
Here i want to trigger this click event

First bind click event on anchor tag
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
then manuaaly trigger click event of 3rd element like given below
$('.select-option a').eq(2).click()
or
$('.select-option a').eq(2).trigger("click")

you can use jquery's trigger method
function init_swatches() {
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
$('.select-option a').eq(2).trigger("click");
}

I'm not sure you're wanting to trigger the click event, but rather use the click event to set the selected class. Something like this might be more suitable:
$(document).ready(function() {
$(document).delegate(".select-option", "click", function(e) {
if ($(this).hasClass("selected") == false) {
$(".select-option.selected").removeClass("selected");
$(this).addClass("selected");
}
});
selectNthImage(3);
});
function selectNthImage(n) {
$(".select-option.selected").removeClass("selected");
$(".select-option:nth-child(" + n + ")").addClass("selected");
};
See a jsfiddle here

Related

JQuery duplicate events when create element and set events to class

When I add an item using click event and exists another element with the same class the event is duplicated.
$(".add-first").on("click", function() {
var firstContainer='<div class="second-container"><button class="add-second">add second</button></div>';
$(this).closest(".first-container").append(firstContainer);
$(".add-second").on("click", function() {
$(this).closest(".second-container").append("<br>example");
});
});
$(".add-second").on("click", function() {
$(this).closest(".second-container").append("<br>example");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first-container">
<button class="add-first">add first</button>
<div class="second-container"><button class="add-second">add second</button></div>
</div>
Then when I press one click in add first this duplicate event in each button add second, then when I press click on the second button it has some events, the issue is duplicated event.
Try to implement event-delegation instead of binding an event event every time when you are creating a new button,
$(".add-first").on("click", function() {
var firstContainer = '<div class="second-container"><button class="add-second">add second</button></div>';
$(this).closest(".first-container").append(firstContainer);
});
$(".first-container").on("click", ".add-second", function() {
$(this).closest(".second-container").append("<br>example");
});
DEMO

Attach one time event to dynamically added elements

I have a web page where there is a button, when the button is clicked a Textbox is added to a DIV. Here is a similar code that I'm working with:
HTML
<button class="addText">Add Textbox</button>
<div class="textCont">
</div>
JavaScript
$(document).on("click", ".addText", function() {
var textarea = $("<textarea/>", {class: "newText"});
$(".textCont").append(textarea);
});
$(document).one("focus", ".newText", function() {
alert("Great");
});
Fiddle: http://jsfiddle.net/ErRohitAgg/g3A7T/
What I'm trying to do is to show an alert for first focus of every textbox that is added. But, instead the focus event is executing only once, and not once for each Textbox.
Is there any way the event behaves according to the functionality I need??
Add the event handler to each textarea instead
$(document).on("click", ".addText", function() {
$("<textarea/>", {
'class': 'newText',
one : {
focus: function() {
alert("Great");
}
}
}).appendTo(".textCont");
});
FIDDLE
I would rather do it by adding newclass on first focus:
$(document).on("focus", ".newText", function() {
if(!$(this).hasClass('focused')){
$(this).addClass('focused')
alert("Great");
}});
Working Demo

Capturing an event with jquery

I got a double event to manage. The two events are both "click" and they're handled with jquery. The html is the following:
<div class="siteMap" style="width:23%;">
<h5>Divisione Anticontraffazione</h5>
<span class="menufooter">
<span class="link1">Introduzione</span><br>
<span class="link2">Filosofia</span><br>
<span class="link3">Negozio online</span></span><br>
</div>
Then i have my click events which fires inside the menufooter span and inside every single link span. The code is like this:
$(document).ready(function() {
$('span.menufooter').click(function() {
//my code here
});
$("span.link1").click(function() {
//my code here
});
});
I need an event capturing action, the click on the span menufooter has to fire the event before the click on the span link1 fires. At this point, none of the two events is firing. Any hint?
How about only fire event on .menufooter
$(document).ready(function() {
$('span.menufooter').click(function(e) {
//my code here 1
// Capture Event Propagation
if ( $("span .link1").find(e.target).length>0 ){
//my code here 2
};
});
});
http://jsfiddle.net/9QLtG/
You could prevent the click from bubbling, and then trigger the click on the parent element so whatever is in that handler executes first (unless it's async)
$(document).ready(function () {
$('.menufooter').click(function () {
// fires before ....
});
$("span.link1").click(function (e) {
e.stopPropagation();
$('.menufooter').trigger('click');
// .... this fires, as it's triggered above
});
});
FIDDLE
I would have 1 click listener that listens to the wrapper. You can check the event's target to see if they actually clicked on a link and run code accordingly.
For example:
$(document).ready(function() {
$('.container').click(function(e) {
// Perform action when they clicked in the main wrapper,
// regardless of whether or not it was a link.
console.log("I clicked in the wrapper...");
if ($(e.target).hasClass('link')) {
// Perform action if they clicked on a link.
console.log("...but more specifically, on a link.");
}
});
});
Here's a fiddle that demonstrates this: http://jsfiddle.net/WaYFr/
Try this event.stopPropagation();
$("span.link1").click(function(event) {
event.stopPropagation();
...
});

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

cancel an existing image on click event using jquery

In the actual website, when clicking on an image from thumbnails, it opens a slideshow.
I have created a new onclick event:
$('.thumbnails a').click(function(event) {
//my piece of code
});
How can I cancel the existing on click event, not knowing which selector's been used to trigger the event (parent? child? specific class?)
I have tried things like:
event.stopPropagation()
$(this).stop()
with no success.
RE-EDIT--------------------------------------------------------
html starts with:
<div class="images">
<a title="Voyage itinérant en Boutre" rel="prettyPhoto[product-gallery]" class="zoom" href="http://dev.snorkeling-voyages.com/wp-content/uploads/2013/05/snorkeling-madagascar-001_alefa.jpg" itemprop="image">
<img width="462" height="392" class="yit-image attachment-shop_single" src="http://dev.snorkeling-voyages.com/wp-content/uploads/2013/05/snorkeling-madagascar-001_alefa-462x392.jpg">
</a>
<div class="thumbnails nomagnifier">
<a class="zoom first" rel="prettyPhoto[product-gallery]" title="bateau itinerant madagascar" href="http://dev.snorkeling-voyages.com/wp-content/uploads/2013/05/snorkeling-madagascar-002_alefa.jpg">
<img width="100" height="80" class="yit-image attachment-shop_thumbnail" src="http://dev.snorkeling-voyages.com/wp-content/uploads/2013/05/snorkeling-madagascar-002_alefa-100x80.jpg"></a>
jQuery to change the featured image on thumbnails click:
$('.thumbnails a').click(function(event) {
var destination= $('.images >a');
destination.empty();
$(this).prependTo(".images >a");
$('.images a a img').attr('width','470');
$('.images a a img').attr('height','392');
//replace src string
var src=($('.images img').attr('src'));
var pattern = /[100x80]/;
if(pattern.test(src))
src=src.replace("100x80", "462x392");
$('.images a a img').attr('src',src);
$('.images a a img').attr('class','yit-image attachment-shop_single');
});
#bfavaretto comment helped me localise an existing a .zoom click event (very useful thanks)
(how can I know the js file? )
I have added a
$('.zoom a').click(function(event) {
return false ;
// or event.preventDefault();
});
and this does not prevent the slider from being opened still!
You can remove all other click handlers from an element with .off:
$('.thumbnails a').off('click');
In case the event was delegated, you need something like this:
$(document).off('click', '.thumbnails a');
However, you have to do that from outside your click handler, or it may be too late.
You can use .preventDefault() to prevent the link from executing:
event.preventDefault();
jsFiddle here
You can try using either of the two commented statements:
$('a').click(function(e){
//e.preventDefault();
//return false;
});
I did something else If I understand correclty what you want please take a look
off
off
off
off
and the javascript:
$('a').click(function(event){
event.preventDefault();
if ($(this).attr('data-status') == 'on') {
$(this).attr('data-status','off');
$(this).html('off');
return;
}
var areOn = 0;
$('a').each(function(){
if ($(this).attr('data-status') == 'on') {
areOn++;
}
})
if (areOn == 0) {
$(this).attr('data-status','on');
$(this).html('on');
}
})
http://jsfiddle.net/ERMtg/9/
You can use return false, I think that will do
$('.thumbnails a').click(function(event) {
return false;
});

Categories

Resources