jQuery .on click event doesn't always fire on Ajax loaded content - javascript

I have a page where I dynamically load contents. Inside the $(document).ready I have similar event handlers:
$(document).on("click", ".content_button", function(e){
e.preventDefault();
e.stopPropagation();
// content
});
The problem is that the mouse click only recognised at around 90% of the clicks. It seems totally random. At other times I have to push the same button 4-5 times, and then it works. I have no error in the console, even the CSS part works every time:
div.content_button:active {
top: 2px;
}
I can't seem to find a solution. I use jQuery 1.11, it works like this on Win10, Win7, inside Firefox, and even on iPad or Android.
Do you have any ideas about what can be the problem?
Edit:
data.control contains the .content_button divs (buttons) in HTML.
And here is the part, which loads the buttons:
$.ajax({
url: 'worker.php',
async: false,
cache: false,
type: "POST",
data: { action:"update" },
dataType: "json",
success:function(data) {
if(data.actionresult == 1)
{
$('div#container').hide("slide", { direction: "down" }, 500);
$('div#container').promise().done(function() {
$('div#container').html(data.control);
$('div#container').show();
});
}
else
{
// handle error
}
}
});

$(document).ready(function(){
$(".content_button").on("click", function(e){
e.preventDefault();
e.stopPropagation();
// content
});
});
It must be done like this.

Have you tried with
$(function() {
var count = 0;
$('body').on('click', '.content_button', function() {
count++;
$('#count').html(count);
});
});
https://jsfiddle.net/byexstpq/

Ok, I have found the problem, it is this:
div.content_button:active {
top: 2px;
}
On mouseDown it moves 2 pixels, so it is possible that the link won't be there after a mouseUp - so technically the click event won't fire as the mouseUp happens over another element.
I hope this will help others.

Related

How to call jQuery Lightbox with AJAX

How can I call jQuery Lightbox2 with AJAX.
I am using this function for my project.
$(document).ready(function() {
$(".paylasimi-goster").click(function() {
event.preventDefault();
var id = $(this).data("id");
$.ajax({
url: "gonderiyi_goster.php?msg_id=" + id,
type: 'get',
beforeSend: function() {
$("#loader").fadeIn(100);
},
}).done(function(data) {
$("#loader").fadeOut(100);
$(".sidebar").fadeIn().find(".sidebar-content").animate({
"right": 0
}, 200).html(data);
imgResize(jQuery, 'smartresize');
});
});
$(".sidebar").click(function() {
$(".sidebar-content").animate({
"right": "-565px"
}, 200, function() {
$(".sidebar").fadeOut();
})
});
$(".sidebar-content").click(function(e) {
e.stopPropagation();
});
});
Also I have created this DEMO from jsfiddle. In this jsfiddle you can see there white div. Click any white div then see the right sidebar. So in the sidebar have one image. The problem is here : Lightbox2 does not work when you click on the image.
How can I call Lightbox2 with ajax.
The issue here is the e. stopPropagation() on the .sidebar-content click event which is preventing the lightbox from triggering. You can remove that altogether and inside the .sidebar click event instead call:
$(".sidebar").click(function(e){
var preventClick = $(".sidebar-content");
if (!preventClick.is(e.target) && preventClick.has(e.target).length === 0){
//run the hide animate function + callback
$(".sidebar-content").animate({"right":"-200px"},200,function(){
$(".sidebar").fadeOut();
});
};
});
FIDDLE

To stop document.click function on key up

To hide a div on click on the rest of the page I used
$('#display').click(function(e){
e.stopPropagation();
});
$(document).click(function(){
$('#display').slideUp();
});
Now I want make the function document.click work only if a user is not typing any text in text box with id "mse".
<input type="text" id="mse" name="search">
I tried like this:
$(document).click(function(){
if($( "#mse" ).keyup()){
//do nothing
}else{
$('#display').slideUp();
}
});
But it doesn't worked.
Help me to overcome this problem.
My total code is:
$(document).ready(function(){
$("#mse").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{}
else
{
$.ajax({
type: "POST",
url: "search.jsp",
data: dataString,
cache: false,
success: function(html)
{
$("#smartscreen").html(html).show();
}
});
}return false;
});
$('#mse').focus(function(){
$('#display' ).css( "display", "block" );
});
$('#display').click(function(e){
e.stopPropagation();
});
});
$(document).click(function(e){
$('#display').slideUp();
});
You might want to turn the document's click event on and off. Here are the ingredients for that:
.on() with namespacing of the event
.off()
.focus() and .blur()
Then, depending on what you need, do something like this: when the "mse" element gets focused, turn off the document's click event. When the "mse" element gets blurred, turn the document's click event back on. Example in this JS Fiddle
relevant code from the JS Fiddle:
$('#mse').focus(function(){
$(document).off('click.slider');
$('#display').css('display', 'block');
});
$('#mse').blur(function(){
$(document).on('click.slider', function(e){
$('#display').slideUp();
});
});

ColorBox not picking up script from behind

I'm using a colorbox to show some images. The code i use to call the images is:
jQuery(".ImgPop").colorbox({
opacity: 0.4,
rel: 'ImgPop',
iframe: false,
width: '770px',
height: '680px',
scalePhotos: true,
current: false
});
This works fine and pops up my images where i can navigate through them.
My problem is on the original page where i call the code above i have a scrip that prevents any right clicking on images using the code:
$(document).ready(function(){
jQuery("img").bind("contextmenu",function(e){
alert('Images are Copyright of this site.');
return false;
});
});
This code works for everything on my site apart from colorbox. Is there any way to pass this script through to the colorbox or am I doing something wrong?
Try with this:
$(document).bind("contextmenu",function(e){
e.preventDefault()
});
Or go with this:
$('img').on('contextmenu', function(e){
return false;
});
Or
$(document).on('mousedown', 'img', function(e){
if(e.which === 3){
$(this).on('contextmenu', function(e){
e.preventDefault();
});
};
});
I found out how to do this...
This is the code I used:
// This is used to prevent right clicks on images within colorbox
jQuery(document).bind('cbox_complete', function(){
jQuery("img").bind("mousedown",function(e){
if(e.which == 3){
alert('Images are Copyright of this site.');
return false;
}
});
});
// This removes the above mousedown event so that outside of colorbox
// the prevent image notification does not show twice.
jQuery(document).bind('cbox_closed', function(){
jQuery("img").unbind("mousedown");
});

live() alternative on() not working jQuery 1.9

I have code do ajax method for loading new content
But I have problem with the new content, the links not applying the action i did like
preventDefault and the ajax method, just after loading the new content
clicking on links make the page reload like there was no ajax code at all
In JQ 1.8 working grate with live() method, but after updating jQuery, not working as it should with on() method
The old code working right and have no problem with it
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
function loadContent(url){
$.ajax({
url: url,
dataType: 'html',
cache: false
}).done(function(html){
var $html = $(html);
$('title').html($html.filter('title').text());
$('#main').replaceWith($html.find('#main'));
$('.nav-menu').replaceWith($html.find('.nav-menu'));
$('.nav-below').replaceWith($html.find('.nav-below'));
});
}
$(function(){
// Get The Content Action
$('.nav-menu li a,#nav-below a,#main a').live('click',function(e) {
href = $(this).attr("href");
loadContent(href);
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
// go top after showing the content
$('html, body').animate({scrollTop:0}, 'slow');
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event){
loadContent(location.pathname);
$('html, body').animate({scrollTop:0}, 'slow');
};
});
</script>
The new updated code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function loadContent(url){
$.ajax({
url: url,
dataType: 'html',
cache: false
}).done(function(html){
var $html = $(html);
$('title').html($html.filter('title').text());
$('#main').replaceWith($html.find('#main'));
$('.nav-menu').replaceWith($html.find('.nav-menu'));
$('.nav-below').replaceWith($html.find('.nav-below'));
});
}
$(function(){
// Get The Content Action, ‡‡=‡=‡=‡=L0000K HERE=‡=‡=‡=‡‡ Not workin JQ 1.9
$('.nav-menu li a,#nav-below a,#main a').on('click',function(e) {
href = $(this).attr("href");
loadContent(href);
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
// go top after showing the content
$('html, body').animate({scrollTop:0}, 'slow');
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event){
loadContent(location.pathname);
$('html, body').animate({scrollTop:0}, 'slow');
};
});
</script>
The problem right here
$('.nav-menu li a,#nav-below a,#main a').on('click',function(e) {
Thank you :)
You don't simply s/live/on, you need to read the documentation of on() to see the changes required to update your code (on is similar to the old delegate()).
If you want to make it work exactly like live(), try...
$(document).on('click', '.nav-menu li a,#nav-below a,#main a', function(e) { });
However, if you can, you're better off choosing the most common persistent ancestor. This means that the events won't have to go all the way up to document to be handled. For example, body probably covers 99.9% of situations. However, it's probably more like #some-container.
for easy usage you can use something like this:
$.fn.follow = function (event, callback) {
$(document).on(event, $(this).selector, callback);
}
and you can use it like:
$("#myselector").follow("click",function(){
/*some callback code*/
});
you can still use event data in your plugin
$("#expform").follow("submit",function(e){
e.preventDefault();
});

jQuery, Shadowbox and AJAX

I would like to load some content using AJAX and Shadowbox
Basically I would like the user to goto a page in case javascript is off. So this is what I want to do :-
1) Cancel the click event i.e the User must not go to a different page.
2) Load content using ajax function in jQuery
3) Show the content inside a shadow box
My code works ok until loading content using ajax but the shadowbox is not displayed and the URL is gettin refreshed i guess, everything goes blank.
jQuery(document).ready(function($){
// rounded corners
$('img').addClass('corner iradius16');
DD_roundies.addRule('#nav li a',4,true);
DD_roundies.addRule('.grid',6,true);
$('h2 a').bind('click', function() {
var id = $(this).attr('id');
$.ajax({
url: "/ajax-post.php?p="+id,
success: function(data){
Shadowbox.open({
content: data,
player: "html",
height: 350,
width: 350
});
}
});
return false;
});
UPDATE 1
tried this code, and as soon as the shadowbox loads, the document gets reloaded and white.
Shadowbox.init({
skipSetup: true,
players: ["html"]
});
// LOAD
jQuery(document).ready(function($){
// rounded corners
$('img').addClass('corner iradius16');
DD_roundies.addRule('#nav li a',4,true);
DD_roundies.addRule('.grid',6,true);
$('.post h2 a').bind('click', function() {
var id = $(this).attr('id');
$.ajax({
url: "<?php bloginfo( 'template_directory'); ?>/ajax-post.php?p="+id,
success: function(data){
show_box(data);
}
});
return false;
});
});
//shadowbox
function show_box(html) {
Shadowbox.open({
content: html,
player: "html",
height: 350,
width: 350
});
}
UPDATE 2
Okay got the prbolem, the html that I am getting via ajax has some javascript in it and that is the reason for the page reload.
Why is this happening ? Any ideas ?
Since you're not getting any JavaScript errors try debugging by breaking it down:
Ensure that the binding to and overriding of the click event is functioning properly:
$('h2 a').bind('click', function() {
alert('click even fired');
return false;
});
If that works, check the data that your ajax request is returning:
$('h2 a').bind('click', function() {
var id = $(this).attr('id');
$.ajax({
url: "ajax-post.php?p="+id,
success: function(data){
alert(data);
}
});
return false;
});
The code looks like it should work, so I'm guessing there's either something wrong elsewhere (in which case the first test will likely fail) or you're getting some really odd data returned.
Need to run
Shadowbox.setup('h2 a');
This will reinitialise and bind it to any ajax loaded content

Categories