Event listener if div is reloaded - javascript

In some AJAX query, in response.done I refresh some div and it works fine, the problem is this refresh doesn't refresh also another function(this function fill the content html() of another div inside the refreshed one). I'm thinking for a trick to add an event to listen when that div is reloaded, I lunch my getAmount() function.
I tried to add that function after reloading part in AJAX but it doesn't work.
file1.phtml
ajaxRequest = jQuery.ajax({
...
ajaxRequest.done(function (response, textStatus, jqXHR) {
jQuery("#shopping-cart-table").load(location.href + " #shopping-cart-table"); //Here I reload my div.
});
file2.phtml
function getAmount() {
var some = jQuery(this).attr('data-subtotal');
jQuery('#shopping-cart-table .data').each(function(){
jQuery('.ship-cart-vendor-header').each(function(){
jQuery(this).find('.not-reached').html(some);
});
});
}

You've to call your getAmount function in the load callback, what mean after the complete reloading :
jQuery("#shopping-cart-table").load(location.href + " #shopping-cart-table", function(){
getAmount();
});

Related

when scroll down, data is loaded by ajax but click trigger is not working jquery

i face a problem of jquery click function when i scroll down in list.
in list, data is loaded by ajax request and when i scroll down then click function (trigger) is not working.
when i not scroll down, ajax data is not loaded then click function is working.
i'm confuse why this happened. i used following triggers below but not success.
on()
click()
bind()
load()
delegate()
i'm sending you code. this is code below. Please help me to sort out.
$(window).ready(function(){
$(".like").on("click", function(){
var id = $(this).attr('data');
// alert(id);
$.ajax({
url: "/stores/addLike",
type: 'GET',
data: {
id: id
},
error: function (data) {
console.log(data);
},
success: function (data) {
console.log(data);
if(data == "liked"){
alert('Sorry, you have already liked this beat.');
}else if(data == "notlogin"){
alert('Please login first to like a beat.');
window.location = "https://demo.amplifihub.com/login";
}else{
$(".likes"+id).text(data);
}
}
});
});
});
instead of $(".like").on("click", function(){ }); use $(document).on("click", ".like", function(){}); or use any static parent dom element to preserve the DOM event. I believe you are generating .like class element on scroll ajax call.

Set page history with page content by js

I've used pace.js but the problem with pace was, the loading animation was shown after the page was completely loaded.
So, i have tried and made a solution, onclick every link on the page, jquery grabs and stops the event from the browser going direct to the link, and sends a ajax get request to that link. While the page is loading, it shows an animation on the current page. After the page is completely loaded, it replaces the whole current document with the received data and replacing the page url in the address bar.
<script type="text/javascript">
$( document ).ready(function() {
$('a').click(function() {
var dt;
if (/#/.test(this.href)) {
return true;
}else{
document.getElementById("before-loader").style.display= "block";//show loading animation
var that = this;
$.ajax({
type: "GET",
url: that.href,
success: function(response){
document.open();
document.write(response);
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", that.href);
document.close();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
document.getElementById("before-loader").style.display= "none";//hide loading animation
}
});
return false;
}
});
});
</script>
The problem is on clicking browser back button, the url in the address bar is changing but the page content still remains the same.
How can i overcome this problem?
Update
se0kjun's answer didn't solved my problem(i was expecting it to work after copy/paste the code provided) but put me in the right direction. After some study and rewriting the flow, it works, but i am still confused why it works.
$( document ).ready(function() {
$('a').click(function() {
if (/#/.test(this.href)) {
return true;
}else{
window.history.pushState(null, 'Production Workflow & Sales Management', this.href);
loadContent(this.href);
return false;
}
});
});
function loadContent(href) {
document.getElementById("before-loader").style.display= "block";
$.ajax({
type: "GET",
url: href,
success: function(response){
document.open();
document.title = response.pageTitle;
document.write(response);
document.close();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
document.getElementById("before-loader").style.display= "none";
}
});
}
window.onpopstate = function(event) {
link = location.pathname.replace(/^.*[\\/]/, ""); // get filename only
loadContent(link);
};
Maybe i should study more.
I think you want to popstate event.
When you click a link, ajax request to that.href. After that, if request is successful, you would get response and call pushstate.
When you click a back button, popstate event is triggered. you can load previous page in popstate event handler.
Following to usage example of popstate
window.onpopstate = function(event) {
//you add a path in pushstate
$('.container').load(event.state.path);
alert('popstate');
};
Here's a fiddle

Jquery addClass -- Function for New Class

I have a issue in my js file.
This is my Js Code.
<script type="text/javascript">
$(document).ready(function()
{
$(".abc").click(function()
{
$(this).addClass('testingClass');
});
$(".testingClass").click(function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
});
</script>
My HTML :
<button class="abc">Demo</button>
When i load this page in Browser, The addClass function is successfully executing and adding new class named "testingClass".
But When Try to click again t that button (meens : class="testingClass") the alert function does not working. What is the error.
Is JS is not supporting frequent execution of an element ?
Anybody Please help me.
Steps..
One Button has class named abc
When click on it an ajax function will storing current time in database.(ajax function not in stack-code).
after successful ajax response the button class changed to testingClass.
now the class name of the button is testingClass
After some time Click on the Button again (class named:testingClass), i want to call a ajax function with current time of click and store the values in database.
Then the Button class name will changed to old ( abc).
You need to event delegation for dynamic added element
$(document).on("click",".testingClass",function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
Event delegation
Update
For the changed question, you are looking for something like this.
Here is a demo.
$('body').on('click', '.abc', function () {
// event attached to .abc
// updateTime is a method that takes context (this), current timestamp and a function
// we need to send the context so that we have access to the current
element inside the below function which is executed outside the scope
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('testingClass').removeClass('abc');
$('#log').append('Time: ' + data + 'from abc <br/>');
});
}).on('click', '.testingClass', function () {
// event attached to .abc
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('abc').removeClass('testingClass');
$('#log').append('Time: ' + data + ' from testingclass <br/>');
});
});
function updateTime(currentTime, successCallback) {
$.ajax({
context: this, // the context sent from the above methods is used here
url: '/echo/html/',
data: {
html: currentTime
},
method: 'post',
success: successCallback
});
}
Using .one() will help you attach event only once upon multiple clicks.
This handler is executed at most once per element per event type.
I think this is what you are looking for. Adding a handler after the class is added.
$(".abc").click(function(){
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
$(document).ready(function() {
$(".abc").click(function() {
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="abc">Demo</button>

Change css of first div after live click

I want to be able to change the css of a div after I have clicked span.submit-comment.
How would I go about to change the css of that div.
I tried putting the following in the success part of the script:
$('div.news-comment:first').css("background-color", "#000");
But the div just flashes black (as I click) because it's inside the click function. I want the css to persist untill I refresh the page.
Any ideas?
// post news comment
$('span.submit-comment').live('click', function() {
var commentname = $('input#commentname').val();
var commentcontent = $('textarea#commentcontent').val();
var newsid = $('span.view-comments').attr('id');
var datastring = 'commentname=' + commentname + '&commentcontent=' + commentcontent + '&newsid=' + newsid;
$.ajax({
type: "POST",
url: "ajax/post_news_comment.php",
data: datastring,
success: function(){
$('div#news-comments').load('ajax/get_news_comments.php?news_id=' + newsid);
}
});
});
If the comment you are changing the background on is in the #news-comments div you are replacing it with the loaded html from get_news_comments.php in your .ajax callback. No matter where you put your js the element will be replaced.
If so, adding it in a callback for the load in your success function should be ok.
Your css script is ok, but just place it after load function.
Just add a return false at the end of the function for the button click, or pass in the value e and put e.preventDefault(); at the begining or end of the function.
e.g.
$('span.submit-comment').live('click', function(e) {
e.preventDefault();
// your other code.
return false;
});

Jquery UI calendar in ajax loaded dialog

I have link with onclick="open_dialog" which opens jquery ui dialog. It loads its content with ajax and that content loads another content test2.php with ajax that has input tag with class="calendar". Problem is that, if i click on input it won't show any calendar. Maybe somebody knows why?
function open_dialog() {
var url = 'test.php';
var dialog;
if ($('#test').length) {
dialog = $('#test');
} else {
dialog = $('<div id="test" class="type_' + type + '" style="display:hidden;"></div>').appendTo('body');
}
dialog.load(
url,
{},
function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
open: function(event, ui) {
$('.calendar').datepicker();
}
});
}
);
return false;
}
Sorry, but i found the answer:
I had to call calendar in second ajax call like this:
$('#content_in_test_dialog').load(
'test2.php',
function(response, status, xhr) {
$('.calendar').datepicker();
}
);
At first you should to find the problem?
1) first add alert('first line of open_dialog function'); and check is call or not.
2) second check that is calendar added self html content to html page. May be it added self content, but some css style hide it.

Categories