PreventDefault not working for dynamic link - javascript

<a href="#" class="submit-form show-field" data-show-field="#Product" >View products</a>
This link is dynamically added to the dom, and I fire a jQuery function on click
$('body').on("click", 'a.show-field', function(e) {
if (!$(this).attr('data-show-field')) {
return;
}
$($(this).attr('data-show-field')).parent().show();
e.preventDefault();
});
The event fires fine, but page redirects. I cant understand what I've done wrong

You event is fired before you can prevent it.
$('body').on("click", 'a.show-field', function(e) {
e.preventDefault();
if (!$(this).attr('data-show-field')) {
return;
}
$($(this).attr('data-show-field')).parent().show();
/*e.preventDefault(); */
});

If the page redirects then I think your listener is not working well.
Here you are a plunker with a use case.
With and whithout document ready
I donĀ“t know where you put your code, but if it's outside the "document ready" that listener never fires.
$('body').on("click", 'a.show-field', function(e) {
alert("First attemp is attached");
});
$(document).ready(function() {
$('body').on("click", 'a.show-field', function(e) {
alert("Second attemp is attached");
if (!$(this).attr('data-show-field')) {
return;
}
$($(this).attr('data-show-field')).parent().show();
e.preventDefault();
});
});
PD: sorry for my english

Related

jQuery calling on() on dynamically generated it after calling click()

I am trying to develop some code to allow the user show/hide a block level element by clicking a button.
The HTML structure is like below
<div class="chat_container"><a class="crm" href="https://google.com" target="_blank">Chat?</a><button id="close_chat"><</button></div>
I have written a click() function for #close_chat which amongst other things changes the ID of the button to #open_chat. I then use the on() method on #open_chat to modify some classes and ids on various elements. In isolation both these methods work, however when combined they don't work. I have noticed that when I click #close_chat even though the ID changes to #open_chat the original event is still attached to the button. After doing some search I suspected the issue might have been related to events bubbling up, but now I am not so sure, still I added event.stopPopagation() to my click function and I can see it appears to be called correctly. I have also tried using the one() method, this appeared to get closer to the behavior I was expecting at the DOM level but still didn't working
My expected behavior is the click() function is called when the user clicks #close_chat, the event is then unbound allowing the .on() event to be called on #open_chat. Id than of course have to reset the original functionality. My code looks like this
$(document).ready(function () {
var close = "<button id='close_chat'><</div>";
var container = $("<div />");
container.addClass("chat_container");
var crmChat = $("<a />");
crmChat.addClass("crm");
crmChat.attr("href", "https://google.com");
crmChat.attr("target", "_blank");
crmChat.text("Chat?");
console.log(crmChat);
console.log(container);
$(container).insertAfter("#heading");
$(container).prepend(crmChat);
$(close).insertAfter(crmChat);
$("#close_chat").click(function (event) {
$("#close_chat").removeAttr("id").attr("id", "open_chat");
event.stopPropagation();
alert(event.isPropagationStopped());
//return false;
});
$(".chat_container").on("#open_chat", "button", function () {
//$(".crm_chat_container").addClass("animate-open").removeClass("animate-close");
$("#open_chat").html(">").removeAttr("id").attr("id", "reopen");
//event.stopPropagation();
});
});
any help is greatly appreciated
Sam
edit, I have now updated my code to look like so
//onclick function for our close button
$("#close_chat").click(function (event) {
attachClosedChatListner();
});
function attachOpendChatListener() {
$(".chat_container").on("click","#open_chat", function () {
$("#open_chat").removeAttr("id").attr("id", "close_chat");
$("#close_chat").html("<")
$(".crm_chat_container").removeClass("animate-close").addClass("animate-open");
});
//attachClosedChatListner();
}
function attachClosedChatListner() {
$("#close_chat").off('click');
$("#close_chat").removeAttr("id").attr("id", "open_chat");
$("#open_chat").html(">")
$(".chat_container").removeClass("animate-open").addClass("animate-close");
//attachOpendChatListener();
}
What about re-attaching the event?
$("#close_chat").click(function (event) {
$("#close_chat").removeAttr("id").attr("id", "open_chat");
attachOpenChatListener();
event.stopPropagation();
alert(event.isPropagationStopped());
//return false;
});
function attachOpenChatListener() {
$("#close_chat").off('click');
$(".chat_container").on("#open_chat", "button", function () {
//$(".crm_chat_container").addClass("animate-open").removeClass("animate-close");
$("#open_chat").html(">").removeAttr("id").attr("id", "reopen");
//event.stopPropagation();
});
}
I managed to work this out, the click function was causing the problem
//onclick function for our close button
$("#close_chat").click(function (event) {
attachClosedChatListner();
});
I've replaced it with .on and it works now
$(".crm_chat_container").on("click", "#close_chat", function (event) {
$("#close_chat").off('click');
$("#close_chat").removeAttr("id").attr("id", "open_chat");
$("#open_chat").html(">");
$(".crm_chat_container").removeClass("primo-animate-open").addClass("animate- close");
attachCloseChatListener();
event.stopImmediatePropagation();
});
function attachCloseChatListener() {
$(".crm_chat_container").on("click", "#open_chat", function (event) {
$("#open_chat").off('click');
$(".crm_chat_container").removeClass("primo-animate-close").addClass("primo-animate-open");
$("#open_chat").removeAttr("id").attr("id", "close_chat");
$("#close_chat").html("<");
event.stopImmediatePropagation();
});
}
on thing is my click events appears to be firing multiple times, that is after clicking my buttons a few times I see several click events in dev tools.
Anyway, thanks for putting me on the right path

creating an alert that shows when form is submitted

I'm trying to create a function in javascript that gets an alert to show up when you click the submit button. I managed to get the alert to show but it only pops up when you open the page but doesn't work when you click the submit button.
heres the function i created in javascript
function orderTics(){
//creates alert
var orderTotal=35;
alert("Your order total is $"+orderTotal);
}
I called the function in html like this:
<script>
orderTics();
</script>
I'm still very much a beginner so any and all tips will be greatly appreciated
You can use the below.
$("#FormSelector").on("submit", function() {
//Your code goes here
});
You could use the on submit function like this:
$("form.class-name").on("submit", function() {
alert("I've been submitted.");
});
Vanilla JS onsubmit event:
document.querySelector("form.class-name").addEventListener("submit", function() {
alert("I've been submitted.");
}, false);
You can also use the event.preventDefault(); method to prevent the form from going to another page, like this:
$("form.class-name").on("submit", function(event) {
even.preventDefault();
alert("Do stuff");
});
Vanilla JS onsubmit event with event.preventDefault(); method:
document.querySelector("form.class-name").addEventListener("submit", function(event) {
event.preventDefault();
alert("I've been submitted.");
}, false);
NOTE: when you use the event.preventDefault(); method the form won't redirect to the target page, even if you click the ok button in the alert box.
Finally you can just use the click event on the submit button, like this:
$("button.submit-button-class").on("click", function() {
alert("I've been clicked!");
});
Vanilla JS onclick event:
document.querySelector("button.submit-button-class").addEventListener("click", function() {
alert("I've been clicked!");
}, false);
Call your function like this:
<input type="button" value="myButton" onclick="orderTopics();">

off() not working in firefox but working in chrome

I am using a beforeonload function but I want when the user submits the form beforeunload shouldn't work. Here is my code, which works fine in Chrome but not in Firefox.
window.form_submitted = '';
jQuery(document).ready(function() {
jQuery(window).on('beforeunload', function() {
if (form_submitted == '') {
return "Are you sure to leave that page";
}
});
});
jQuery('#form').on('submit', function (e) {
e.preventDefault();
jQuery(window).off('beforeunload');
form_submitted = 1;
site_redirect(resp.payment_url);
}
return false;
});
You have several syntax issues, and you have to place the submit block inside the DOMReady handler, otherwise JS will attempt to bind the event to an element which doesn't yet exist in the DOM. Also note you can remove the the global flag variable as you are unbinding the beforeunload event on form submission. Try this:
jQuery(document).ready(function($) {
$(window).on('beforeunload', function() {
return "Are you sure to leave that page";
});
$('#form').on('submit', function (e) {
e.preventDefault();
$(window).off('beforeunload');
site_redirect(resp.payment_url);
});
});
Also note that by doing a redirect when the form is submit (assuming that's what the site_redirect function is doing) then the content of the form will be lost.

Delaying a jQuery .click function

Ok so I have a little issue here,
$("#WhoAreWe").click(function(){
$("#Image").hide();
$("#Two").slideUp(1000);
$("#Third").slideUp(1000);
$("#Fourth").slideUp(1000);
$("#WhoAreWe").hide();
$("#WhoAreWe2").slideToggle(3000);
$("#IDs").slideDown(3000);
$("#main").click(function(){
alert("Pressed Back");
});
(The alert is just a place holder)
Basically the #main is the entire page, and when any point on the site is pressed. It works fine but the problem is that when I first press #WhoAreWe it also runs the $("#main") function. My problem is that whenever WhoAreWe is pressed, main also runs. I don't want this, I just want it to run when the user clicks anywhere on the page AFTER clicking on WhoAreWe.
Edit:
Just to make it clear, #WhoAreWe is a Div (Text).
main is the ENTIRE PAGE
Try this example:
script
$(function(){
$("#main").on('click', function(e) {
if($(this).hasClass('disabled')) {
return;
}
alert('Its main ....');
});
$("#whoAreWe").on('click', function(e) {
alert('Its Who Are We ....');
$("#main").removeClass('disabled');
});
});
html
<input type="button" value="Who are we ?" id="whoAreWe" />
<input type="button" value="Main" id="main" class="disabled"/>
EDIT
script
$(function () {
$("#main").on('click', function (e) {
if ($(this).hasClass('disabled')) {
return;
}
alert('Its main ....');
});
$("#whoAreWe").on('click', function (e) {
e.stopPropagation();
$("#main").removeClass('disabled');
alert('Its Who Are We ....');
});
});
html
<div id="main" class="disabled">
<div id="whoAreWe">Who Are We ?</div>
</div>
Updated: Previously the "clicked" variable wasn't defined globally... now I've changed it to a global variable...
$(document).ready(function (){
var window.clicked=false;
$("#WhoAreWe").click(function(){
$("#Image").hide();
$("#Two").slideUp(1000);
$("#Third").slideUp(1000);
$("#Fourth").slideUp(1000);
$("#WhoAreWe").hide();
$("#WhoAreWe2").slideToggle(3000);
$("#IDs").slideDown(3000);
window.clicked=true;
});
$("#main").click(function(){
if(!window.clicked){
alert("Pressed Back");
}
});
});
guess this should work fine too
$(document).ready(function(){
$('#whoAreWe').on('click', function(){
$(':not(#whoAreWe)').on('click', function(){
$('#main').unbind('click').on('click', function(){
//unbind and bin click to prevent multi bindings
alert('Pressed Back');
});
});
});
});
and take care you have it wrapped in $(document).ready();. You should put all you actions in there.
FIDDLE
DIV-FIDDLE
DIV-FIDDLE waiting
FIDDLE WITH YOUR HTML AS SAMPLE

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/

Categories