Trigger the event after making the HTML object in JQuery - javascript

I want an event to be triggered after the creation of the corresponding HTML object (href in my case).
I've written this code:
$(document).ready(function() {
$('body').on('click', '#stats-link', function(e) {
console.log('TRIGGERED'); // nothing is logged
e.preventDefault();
$.post('stats.php', {'email': $('#email').val()}, function() {
window.location = $(this).attr('href');
});
});
$('#submit_button').click(function(e) {
e.preventDefault();
...
$('#info').html('<p class="desc">bla bla bla</p>');
...
});
});
So, I make a href object identified by stats-link in the #submit_button function, then I want him to be triggered in the corresponding function (i.e., $('body').on(...), but it doesn't happen. What am I doing wrong?

Did you missed this line:
$('#stats-link').trigger('click');
This will trigger the click event. The code you shared only binds the event. You need to trigger it.
JS:
$(document).ready(function () {
$('body').on('click', '#stats-link', function (e) {
e.preventDefault();
alert('clicked')
$.post('stats.php', {
'email': $('#email').val()
}, function () {
window.location = $(this).attr('href');
});
});
$('#submit_button').click(function (e) {
e.preventDefault();
$('#info').html('<p class="desc">bla bla bla</p>');
$('#stats-link').trigger('click'); //This is where you trigger the click.
});
});
Working Demo: http://jsfiddle.net/lotusgodkk/artaq4xj/

What is e? Are you sure the click event isn't actually working, but just giving you a script error and bailing out before it does anything? Your callback function does not define the passed in event parameter e.
$('body').on('click', '#stats-link', function() { // <-- No e parameter supplied.
e.preventDefault(); // <---- What is e?
...
}

Your preventDefault() parameter is lacked :
$('body').on('click', '#stats-link', function(event) {
event.preventDefault();
$.post('stats.php', {'email': $('#email').val()}, function() {
window.location = $(this).attr('href');
});
});

Related

JQuery click same button with different class

I have a button with class name test-button test-button--check. After clicking test-button--check it should do something and be replaced by class test-button--reset
For test-button--reset I want to write another function, but It doesn't work. Because, the previous function executes again.
$(".test-button--check").on("click", function() {
alert("Check is clicked");
$(this).removeClass("test-button--check").addClass("test-button--reset");
});
$(".test-button--reset").on("click", function() {
alert("Reset is clicked");
$(this).removeClass("test-button--reset").addClass("test-button--check");
});
What can I do?
Thanks
You can write your code inside the document.ready in this way
$(".test-button--check .test-button--reset").on("click", function(e) {
e.preventDefault();
var obj=$(this);
if($(obj).hasClass('test-button--check')){
alert("Check is clicked");
$(this).removeClass("test-button--check").addClass("test-button--reset");
}
if($(obj).hasClass('test-button--reset')){
alert("Reset is clicked");
$(this).removeClass("test-button--reset").addClass("test-button--check");
}
});
Try using .off() to remove an event handler, in this case, it is click.
Should be something like this:
$('.test-button.test-button--reset').off().click(function() {...});
I think this will work:
var check = function checkFunc() {
alert('Check is clicked!');
$(this).addClass('test-button--reset').removeClass('test-button--check');
$('.test-button--reset').unbind('click',check);
$('.test-button--reset').bind('click',reset);
}
var reset = function resetFunc() {
alert('Reset is clicked!');
$(this).addClass('test-button--check').removeClass('test-button--reset');
$('.test-button--check').unbind('click',reset);
$('.test-button--check').bind('click',check);
}
$('.test-button--check').bind('click',check);
Using bind and unbind

JQuery anchor link selector issue

I'm trying to select the list anchor link using jquery. Though 'list' link doesn't exist in the page as shown in the console output, it seems 'click' is still getting triggered. What could be causing 'list' and 'add' to trigger?
I have this simple code using jquery 1.10.2:
<!-- List -->
Delete
Add
<script>
jQuery(document).ready(function($) {
if ($('a[href$="#list"]').length>0){
console.log('list found');
}else{
console.log('list not found');
}
function opentab(value){
console.log('opentab: ' + value );
//perform task here
}
$(document).on('click', 'a[href="#list"]', opentab('list'));
$(document).on('click', 'a[href="#add"]', opentab('add'));
});
</script>
console output:
list not found
opentab: list
opentab: add
Here's jsfiddle link: http://jsfiddle.net/2FHf6/
you need to declare a function in the event that when this event occurs call this function, currently the method inside event is called on page load as your way of calling is not right:
do like this:
$(document).on('click', 'a[href="#list"]', function(){
opentab('list')
});
$(document).on('click', 'a[href="#add"]', function(){
opentab('add')
});
UPDATED FIDDLE
$(document).on('click', 'a[href="#list"]', function(e){
opentab('list');
});
$(document).on('click', 'a[href="#add"]', function(e){
opentab('add');
});
Demo:
http://jsfiddle.net/XJhN6/
See this updated fiddle.
When you want to call a function on an event triggered and the function needs to pass values, you have to do it in an "wrapper" function, like this:
jQuery(document).ready(function($) {
if ($('a[href$="#list"]').length>0){
console.log('list found');
}else{
console.log('list not found');
}
function opentab(value){
console.log('opentab: ' + value );
//perform task here
}
$(document).on('click', 'a[href="#list"]', function() {
opentab('list');
});
$(document).on('click', 'a[href="#add"]', function() {
opentab('add');
});
});
Otherwise it will be called when the event listener is set, not on the actual event.

jquery: Callback not received on clicking of button

I need to send a request on click of button but callback is not received on firing of click event of the button.
Following is code snippet:
$(document).ready(function () {
var counter = 0;
$("#trail").click(function () {
$("#dialog").dialog();
if (counter < 1) {
$("#searchboxdiv").after('<input type="text" id="searchbox">');
$("#searchbox").after('<input type="button" id="searchbutton" value="search">');
counter++;
}
});
$("#searchbutton").click(function () {
var dataToSend = null;
$.ajax({
data: dataToSend,
url: "FormHandler",
success: function (result) {},
beforeSend: function () {
dataToSend = $("#searchbox").val();
}
});
});
$("#searchboxdiv").on('click', "#searchbutton", function(){
var data = null;
});
});
I added the textbox in the dialog box dynamically and on click of button in dialog box, callback is not received
Your options:
Use event delegation. Bind the click to immediate static parent like this :
$("#searchboxdiv").on('click', "#searchbutton", function(){ });
Or, bind it to the document.
$(document).on('click', "#searchbutton", function(){ });
Or, move the existing click after counter++;, ie., inside $("#trail")'s click handler.
For more info, see on()
Use event delegation (for dynamically added #searchbutton)
$('#searchboxdiv').on('click',"#searchbutton",function(){
http://learn.jquery.com/events/event-delegation/

Jquery: block onclick div action when click in other object inside

I have this situation: http://jsfiddle.net/Lm7ac/4/
$(".more").hide();
$(document).on("click", ".btn",function() {
alert("hello");
});
$(document).on("click", "div.post",function() {
var morediv = $(this).find(".more");
morediv.slideToggle('fast');
});
I need to keep ".more" closed(or open) when click in ".btn".
How can i do that?
Thanks
Use event.stopPropagation():
$(document).on("click", ".btn",function(event) {
event.stopPropagation();
alert("hello");
});
...note the event argument to the callback, make sure to include it as above.
http://jsfiddle.net/KJ5Uv/
Cheers
Just return false at the end of the .btn click event handler.
$(document).on("click", ".btn",function() {
alert("hello");
return false;
});
When you return false in a jQuery event handler it's like calling event.preventDefault() as well as event.stopPropagation() at the same time.
Here is a demo: http://jsfiddle.net/Lm7ac/5/
Docs for event.preventDefault(): http://api.jquery.com/event.preventDefault/
Docs for event.stopPropagation(): http://api.jquery.com/event.stopPropagation/

Wrap existing jquery event with defaults

I'm trying to figure out how I can wrap the click event. Eg this is the code I want.
$("#test").aclick(function() {
alert('hi');
});
The only thing that aclick does is use the e.preventDefault automatically.
Is it something like?
$.fn.aclick = function(e) {
e.preventDefault();
return $.fn.click.apply(this, arguments);
});
Thanks.
When binding a handler, the event object e doesn't exist yet. You need to create a default event handler that calls the supplied one:
$.fn.aclick = function (handler) {
return this.each(function () {
var el = this;
$(el).click(function (e) {
e.preventDefault();
handler.call(el, e);
});
});
};

Categories