First time posting here:
I want to know if it's possible to do this. If not what's the best approach. All I want is to attach click events to a list of anchor links and use $.get() to reload the icons. There is reason I am trying to do this is because when I use the usual $(this).on('click'), it works fine but the reloaded anchor links don't respond to the js script any more:
var wishlistBtn = $('.zoa-wishlist');
wishlistBtn.each(function(){
$(document).on('click', $(this), function(){
var url = $(this).attr('href');
$.get(url,function (data, textStatus, jqXHR) {
if(textStatus == 'success'){
$('div#product-button-group').load(location.href + ' div#product-button-group > *'); //Refresh the anchor links
}
});
return false;
});
});
You can do:
$(document).on('click', ".zoa-wishlist", function(){
/* ... */
});
Related
I'have and AJAX post request:
$(document).ready(function() {
$("span").click(function(e) {
e.preventDefault();
e.stopPropagation();
var URL = "someURL";
$.post(URL, this.id, function(data, status) {
var val = parseInt(document.getElementById(this.data).innerHTML)
document.getElementById(id).innerHTML = val + 1 ;
document.getElementById(id).disabled=true;
});
});
});
Read
<span id="${book.id}">
This script is working as expected; a button with number in it increase by one.
The problems are:
A refresh of the page occurs. On button click it reloads all on the page.
I'm not able to disable the button after the change
In short I need a count button which increase by 1 and can be changed once per user.
Update It seems that reload it's related to another function defined as
$(document).ready(function() {
So i have one in the body and one in the head.
Of course it refreshes the page, you're sending it a link to go to via href. Instead, remove the href, and put an onclick event and handler. Replace your anchor tag, with this:
<a onclick="runFunction()">Read</a>
And replace your script, with this.
<script>
function runFunction(){
$(document).ready(function(){
$("span").click(function(e){
e.preventDefault();
e.stopPropagation();
var URL="someURL";
$.post(URL,
this.id,
function(data,status){
var val = parseInt(document.getElementById(this.data).innerHTML)
document.getElementById(id).innerHTML = val + 1 ;
document.getElementById(id).disabled=true;
});
});
});
}
</script>
I'm creating a website where I'd liked to transition between pages seamlessly (like an app). To do that I've settled on ajax-ing the content I need from the requested page with a preloader in between as a transistion. I have the following code:
var url = "";
var historyUrl = "";
$('a').on('click', function(e){
url = $(this).attr("href");
historyUrl = window.location.pathname;
e.preventDefault();
$('#wrap main').removeClass('active');
$("#wrap main").load(url + " #wrap main", function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == "success") {
setTimeout(function() {
$('#wrap main').addClass('active');
}, 1000);
history.pushState(null, null, url);
}
if (textStatus == "error") {
// Error out
}
});
e.stopPropagation();
});
$(window).on('popstate', function(){
$('#wrap main').removeClass('active');
$("#wrap main").load(historyUrl + " #wrap main", function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == "success") {
setTimeout(function() {
$('#wrap main').addClass('active');
}, 1000);
}
if (textStatus == "error") {
// Error out
}
});
});
As you can see I'm triggering on all a tags in order to test this out. This code works fine for the most part. If I go to the first page and click a link I successfully transition to the second page without the browser reloading. The URL changes and the history is pushed. If I then click the back button I will end up back on the first page successfully too.
The problem occurs thereafter; if I then proceed to click the same link I clicked on the first page the first time, it will ignore the on click function and just load the second page as a standard browser would.
i can't figure out why this would happen. I think it's something to do with the pushState but I can't quite put my finger on it.
Am I missing something obvious here?
Thanks
When you dynamically load content, events are not automagically bound to elements. That's why after dynamically changing back to the first page, there is no event handler for the click on the link.
Change
$('a').on('click', function(e){
to
$(document).on('click', 'a', function(e){
and it should work.
This defers the click event to the document (which is not changing) and executes the callback function if the selector in the second argument ('a') matches the event target.
I have the following script I've written.
<script>
$(document).ready(function(){
$('a').data('loop',true);
$('body').on('click', 'a', function(event){
console.log($(this).data('loop'));
if ($(this).data('loop') == 'true') {
console.log('hit');
event.preventDefault();
caller = $(this);
$(this).data('loop',false);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
$(caller).click();
}
});
} else {
console.log(event.isDefaultPrevented());
console.log('miss');
$(this).data('loop',true);
}
});
});
</script>
It works, sends me the details I want etc etc. BUT!!!
When I click a link, It fires off the details to me via Ajax, then it's meant to "click" the event again, which it does! but the event does not fire it's normal action. So When clicking a link to another page, I would go to that other page... that's not happening.
If I comment out the line event.preventDefault(); Then the event fires as I would expect...
So to me it looks like the event.preventDefault is executing even though it's not meant to be during the second call...
Sorry if this is a bit complicated to understand. I don't quite understand what's happening myself.
Is it possibly a bug, or is there something that I've done that has caused this?
I didn't think I could, but I have successfully made a jsfiddle for this.
https://jsfiddle.net/atg5m6ym/2001/
You can try this and not worry about the "loop" anymore:
$(document).ready(function () {
$('body').on('click', 'a', function (event) {
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
window.location.href = linkref; // Redirect happens here
}
});
});
});
UPDATE
There's a few issues to note here:
1) Some links don't require a redirect (as noted, bootstrap model links that control showing/hiding or within document anchors
To correct this it really depends on the case. Usually bootstrap adds specific classes or data attributes to the links so you can do something like.
$('body').on('click', 'a:not(list of things to exclude)'..
Personally I'd instead define the links I wanted to track as :
<a href=<link> data-tracked='true'...
<script>
$('body').on("click","a[data-tracked='true']"...
Or if you want to track most links with a few exceptions you can:
<a href=<link> data-tracked='false'...
<script>
$('body').on("click","a:not([data-tracked='false'])"...
Or more generally:
<script>
$('body').on("click","a", function () {
if ($(this).attr("data-tracked") == "false" || <you can check more things here>){
return true; //Click passes through
}
//Rest of the tracking code here
});
The following if statement will return true whenever the data-loop attribute exists against an element, regardless of it's value:
if ($(this).data('loop')) {
It needs to be changed to check for the value:
if ($(this).data('loop') == 'true') {
When you assign anything to be the value of an element attribute it becomes a string and, as such, requires a string comparison.
Event.preventDefault() is not being executed second time.
Link redirection happens when the method is completed.
So in your case redirection will happen when complete method of ajax call is completed.
lets say, we have event1 and event2 object in the code. event1 is the object in the ajax call method and event2 is the event object in recursive call (second call) method.
so when link is clicked second time , we still have complete method to be executed. as soon as it returns to the complete method of ajax call, it finds the event1 is having preventDefault property true and it does not redirect.
Try this ;)
$(document).ready(function(){
$('body').on('click', 'a', function(event){
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({
linkref: linkref,
linkpos: linkpos,
screenwidth: screenwidth
});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
/* To temprary block browser; */
async: false,
data: "json=" + json_data,
complete: function(jqXHR, status){
/* add class **ignore** to a element you don't want to redirect anywhere(tabs, modals, dropdowns, etc); */
if(!caller.hasClass('ignore')){
/* Redirect happens here */
window.location.href = linkref;
}
}
});
});
});
I've got this function:
$(document).ready(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
My page loads content with favourite buttons, but after Ajax call and generated additional new content the function doesn't work when you click new content's buttons. What could be not right?
That is because you are using dynamic content.
You need to change your click call to a delegated method like on
$('.post_button, .btn_favorite').on('click', function() {
or
$("body").on( "click", ".post_button, .btn_favorite", function( event ) {
Instead of this:
$('.post_button, .btn_favorite').click(function() {
do this:
$(document).on('click','.post_button, .btn_favorite', function() {
on will work with present elements and future ones that match the selector.
Cheers
class-of-element is the applied class of element. which is selector here.
$(document).on("click", ".class-of-element", function (){
alert("Success");
});
If you know the container for .post_button, .btn_favorite then use
$('#container_id').on('click', '.post_button, .btn_favorite', function () { });
so if '.post_button, .btn_favorite' are not found then it will bubble up to container_id
else if you don't know the container then delegate it to document
$(document).on('click', '.post_button, .btn_favorite', function () { });
Reference
I am not sure if I am getting your question right but you may want to try..
$.ajax({
url: "test.html"
}).done(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
Just try to paste your code inside done function.
Hope it helps :)
EDIT:
I also notice you are missing }); on your question.
The following worked for me
$(document).ready(function(){
$(document).bind('contextmenu', function(e) {
if( e.button == 2 && jQuery(e.target).is('img')) {
alert('These photos are copyrighted by the owner. \nAll rights reserved. \nUnauthorized use prohibited.');
return false;
}
});
});
You need to bind the jQuery click event once your ajax content is replaced old content
in AJAX success block you need to add code like here new response html content one a tag like
Click Me
So you can bind the new click event after change the content with following code
$("#new-tag").click(function(){
alert("hi");
return false;
});
I have the following two functions that work great:
$(function(){
$('.trash_can a.delete').live('click', function(event) {
event.preventDefault();
var link = $(this);
$.post(link.attr('data-href'),
{
promo_id: link.attr('data-promo_id')
},
function(data) {
$('#page').html(data.html);
});
console.log('Clicked Delete');
});
});
$(function(){
$('#add-mod-form').bind('ajax:success', function(evt, data, status, xhr){
data = $.parseJSON(data);
// console.log(data.success);
if (data.success == true) {
$('#page').html(data.html);
$('#page box_bc').html()
}
else {
}
});
});
As data is received for page, I would also like to reload a static html element, $('#page box_bc') - How do I do this simple task with Jquery? Notice, i've tried it above, and that part does not work as planned.
Thanks
Use:
var $dataHtml=$(data.html);
$('#page box_bc').html($('#page box_bc',$dataHtml));
It is not very clear to me what you are trying to achieve. If the element is static what is the point trying to refresh it ? In case its content somehow depends on other elements of page : then it has to be reconstructed.
The code you have written fails because :
$('...').html()
returns the html content of that element. It does not do anything to the content. Probably it would be better if you could elaborate more on the context and purpose of the code.