Timmy Von Heiss Timmy Von Heiss - 2 months ago 6
jQuery Question

how do i rerun a function and update variable values?

This code below works correctly, however it only runs the first time because the variables are not getting updated on the completion of the function. I can tell from the return of

console.log($(xyz))
only the initial value,
#100
is returned.

$(document).on('page:change', function () {
var xyz = $('.nextinst').last().attr('href')
var mod = $('.modal'+xzy)
var turn = $('.pagination .next_page a').attr('href')
var craw = $('.glyphicon-chevron-right').last()
$(craw).on('click', function() {

if (!$(mod).size() > 0) {
$.getScript(turn);
}
setTimeout (function() {
$(xyz).modal()
}, 1000);
});
});


I have searched several topics about setTimeout and SetInterval but I have not gotten anything to work correctly.

Edit:

I have an instagram like web app where a thumbnail is displayed on the main page and a modal displays the full image. the modals can be clicked through with previous and next. it is a rails project, the photos are paginated 9 at a time. that means that when in the modal, if you click previous, but the previous photo has no yet been loaded into the DOM, it will not load.

var xyz = $('.nextinst').last().attr('href')
returns the
href
which is the
id
of the photo that the last previous button in the DOM is linking towards. So if photos #1-9 are already paginated,
xyz = #10


var mod = $('.modal'+xzy)
this is going to be used in the
if statement
in the function to check if the
modal
for that picture has been loaded in the DOM yet.

var turn = $('.pagination .next_page a').attr('href')
this is the href link to the next page of photos.

var craw = $('.glyphicon-chevron-right').last()
is the last previous button.

so what happens is that when the last previous button is clicked, it checks if the object/photo exists in the DOM, if it does not, then the next page of photos are paginated. then the modal for that photo is opened in the
setTimout
function.

This all works correctly, however after all of this is done, I need it to all start again and for
xyz
to be given a new value. From the above example. We start with photos #1-9,
xyz
=
#10
. Then we add 9 more photos, so we now have photos #1-18 loaded in the DOM. Now when the function restarts
xyz
should equal
#19
.

Answer

With turbolinks 5 you use the following wrapper:

$(document).on('turbolinks:load', function(){

});
Comments