Trigger click event of dynamic loaded content from ajax call - javascript

Unable to trigger click event for an dynamically loaded content from ajax call. Tried to use trigger method but guess I am missing something here.
$("#call-setup").on("click", function () {
var $this = $("#settings")
var url = $this.data("link")
loadwifinetworks(url);
//$("#connectivity").trigger("click")
});
async function loadwifinetworks(url) {
await new Promise((resolve) => {
$.get(url, function (context) {
$("#contentArea").html(context);
resolve("success")
});
});
//$('body').find('#connectivity').trigger('click');
// $('#contentArea').find('#connectivity').trigger("click")
}

Related

jQuery - trigger("click") not working after e.preventDefault()

I'm trying to perform async operation right before browser redirects user to http://example.com on click.
So, after the ajax call I'm clicking currentTarget again to redirect but it doesn't work.
<a class="notic_click" href="http://example.com">Button</a>
<a class="notic_click" href="http://example.com">Button</a>
$(".notic_click").on("click", function(e, options) {
options = options || {};
// if it hasn't been clicked already
// run this
if( !options.hasClicked ) {
e.preventDefault();
const self = this;
// some other code
$.get("http://example.com/hello")
.always(function() {
$(self).trigger("click", {hasClicked: true});
});
} else {
// I got here, that means e.preventDefault didn't get called and it should redirect
console.log("should redirect but not redirecting");
}
});
I tried $(self).off() right before the trigger, but to no avail.
I have already tried this:
window.location.assign(e.target.href);
and this works. But I'm curious as to what is causing the above not to work.
Browser: Mozilla Firefox (78.0.2)
try this out:
$(".notic_click").on("click", function(e) {
if( e.isTrusted) {
e.preventDefault();
const self = this;
// some other code
$.get("http://example.com/hello")
.always(function() {
$(self).click();
});
} else {
// I got here, that means e.preventDefault didn't get called and it should redirect
console.log("should redirect but not redirecting");
}
});
You can read more about is trusted here: https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
Try it with this code piece. You seem to have a logic problem in your code. Since you prevent the default, you should "return" to the default behaviour:
<a class="notic_click" href="http://example.com">Button</a>
<a class="notic_click" href="http://example.com">Button</a>
<script>
$(".notic_click").on("click", async function (e, options) {
options = options || {};
e.preventDefault();
console.log('do task here');
await new Promise(resolve => setTimeout(resolve, 3000));
console.log('timeout end');
await new Promise(resolve => setTimeout(resolve, 3000));
window.location = this.href;
});
</script>
Your code appears to work fine in isolation. That being said, a better approach would be to always call preventDefault() to stop the page redirection and then make your async AJAX request. When that request completes you can then use window.location.assign() to redirect the user.
$(".notic_click").on("click", e => {
e.preventDefault();
// I'd suggest putting a loading spinner in the UI here to make it clear
// to the user that their request is in process.
$.get("http://example.com/hello").always(() => {
window.location.assign(e.target.href);
});
});

ajax:success callback doesn't fire after conversion from Coffeescript to ES6

I have some ajax Form on my page.
I create a class to manage the behaviour of the buttons, and I have to change the class after the ajax success.
export class Following {
constructor(element) {
element = $(element);
this.follow = element.find('.follow');
this.unfollow = element.find('.following');
this.followForm = this.follow.parents('form');
this.unfollowForm = this.unfollow.parents('form');
this.bindClicks();
}
bindClicks() {
this.followForm.on('ajax:error', this.trySignIn);
this.followForm.on('ajax:success', event => {
console.log('follow success')
});
this.unfollowForm.on('ajax:success', event => {
console.log('unfollow success')
});
}
static init() {
$('.follow-unfollow-buttons').each((i, el) => new Following($(el)));
}
};
When I submit the form, the ajax call is a success, but I cannot intercept the callback. Why?
Solved, I'm using jquery-ujs instead of rails-ujs

Undo preventDefault() after API call

I am writing external script to check availability for e-commerce store. When "Add to basket" button is pressed, I'm calling my API and checking if product is available to order. However, I don't know how to undo preventDefault(). When condition is true, event under button should continue and product should be added to basket as without the script.
button.addEventListener('click', (event) => {
event.preventDefault();
fetch(`https://example.com/api.php?part=${partId}`)
.then(function (response) {
return response.json();
})
.then(function (jsonRes) {
console.log(JSON.stringify(jsonRes));
if (jsonRes.part.partFound == true) {
console.log('Found! Processing...');
// REMOVE preventDefault() and process
} else {
console.log('Not found! Aborting...', partId);
}
});
});
If your button is type="submit" change it totype="button"`. This
a) Won't submit the form
b) Means that you don't have to use preventDefault to prevent the form from submitting
That simply means you're left to decide how you want the data to be submitted, and you can either do that with another AJAX call to an API endpoint, or by submitting the whole form to the server - whichever is your setup.
// Grab the form and button, and add an event
// listener to the button
const form = document.querySelector('form');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
// Fake API call
function fakeAPI() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`API called!`)
}, 2000);
});
}
function handleClick() {
console.log('Clicked');
fakeAPI(2000).then(data => {
// If partfound submit the form data
// Either another fetch call to post the data,
// or `form.submit()` to post the whole form instead
});
}
<form>
<button type="button">
Click
</button>
</form>
you can try something like code below:
async function apiCall(onSuccess, onError) {
fetch(`https://example.com/api.php?part=${partId}`)
.then(function (response) {
return response.json();
})
.then(function (jsonRes) {
console.log(JSON.stringify(jsonRes));
if (jsonRes.part.partFound == true) {
console.log('Found! Processing...');
onSuccess(jsonRes);
} else {
console.log('Not found! Aborting...', partId);
onError();
}
});
}
button.addEventListener('click', (event) => {
// show loading or something
apiCall(function (response) {
// success
}, function () {
// error
});
});

I need to force the event play in a video of vimeo when I decide to call it

I have the next code in JSFIDDLE
If i call the function with a button onclick all work's well but if i want call the function after a jquery event (as document ready or scroll) he tries it but does not play the video. ¿Any solution?
Here the function JS:
var ActionsVimeo = {
forceAutoplay: function(){
jQuery(".forceAutoplay").each(function(){
var player = new Vimeo.Player(jQuery(this)[0]);
player.ready().then(function() {
player.play().then(function () {
alert("Chimichangas it's alive!!");
}).catch(function (error) {
alert("No tacos remain!!",error);
});//.play();
});
});
},
};
Can call the function with ActionsVimeo.forceAutoplay();

popstate HTML 5 event being fired multiple times

Hi i am using the following code to load a part of page dynamically using jquery
loadNextBackInPage_URL = null;
function callBackFunctionLoadNextBackInPage(data)
{
//alert(data);
$("#left").fadeTo(100,1);
var data = $(data).find( '#left' );
$("#left").html(data);
if(supports_history_api())
{
history.pushState(null, null, loadNextBackInPage_URL);
window.addEventListener("popstate", function(e) {
alert('s');
loadNextBackInPage(location.pathname);
});
}
else
{
}
}
function loadNextBackInPage(url,parm)
{
//alert(url);
loadNextBackInPage_URL = url;
$("#left").fadeTo(100,.2);
$.post(url,parm,callBackFunctionLoadNextBackInPage,'html');
}
The loading part and even changing the browser URL is working. but why is the PoP state function being fired multiple times?
I call loadNextBackInPage() originally through an onclick function.
I got it solved from here in codingforums
think you keep adding "popstate"
listeners over and over ...
Program logic:
Page loaded
onclick will execute loadNextBackInPage()
Start a $.post() Request and fire "callBackFunctionLoadNextBackInPage" on completion
pushState()
Register an event listener for "popstate"
When "popstate" fires, execute loadNextBackInPage() and return to step 2
So step 4 will be executed over and
over which will register new event
listeners. Every time "popstate" fires
all the event listeners will execute
Try to move the addEventListener
method call out of this loop
So from those i derived a workaround and also corrected location.pathname to location.href
The corrected code:
loadNextBackInPage_URL = null;
popEventListnerAdded = false;
function callBackFunctionLoadNextBackInPage(data)
{
//alert(data);
$("#left").fadeTo(100,1);
var data = $(data).find( '#left' );
$("#left").html(data);
if(supports_history_api())
{
history.pushState(null, null, loadNextBackInPage_URL);
if(!popEventListnerAdded) {
window.addEventListener("popstate", function(e) {
loadNextBackInPage(location.href);
});
popEventListnerAdded = true;
}
}
else
{
}
}
function loadNextBackInPage(url,parm)
{
//alert(url);
loadNextBackInPage_URL = url;
$("#left").fadeTo(100,.2);
$.post(url,parm,callBackFunctionLoadNextBackInPage,'html');
}

Categories