jpo45 jpo45 - 7 months ago 13
Javascript Question

Why is the back button on the browser breaking this code? It works otherwise

This code ensures that when an image is clicked on a page of portfolio images to go to the corresponding gallery, the image that was clicked on shows up as the first image. It does this by comparing chars from the src attributes and using .prependTo. It all works fine when I navigate back and forth between the portfolio and gallery pages using the links on the pages, but it all gets wonky when I use the back button on the browser, sometimes prepending over and over. Is it something to do with the click event firing over and over? I'm not sure...

$(document).on('click',"a.project",function(){
$("a.project").on('click', function(event) {
var portfolioLastTwoChars = $(event.target).attr('data-src').slice(-8, -4);
var galleryLastTwoChars = $("img").first().attr('data-src').slice(-8, -4);
if (portfolioLastTwoChars === galleryLastTwoChars) {
return;
} else {
var prePendedImage = $("div").children('img[alt*=' + portfolioLastTwoChars + ']').not(".loaded");
$(prePendedImage).not(':first').remove();
prePendedImage.prependTo("div.image-list");
$('div.image-list > img:not(:first-child)').remove();
}
});
});

$( document ).ready(function() {
$("a.project").eq(0).trigger('click');
});

Answer

I believe this may be due to the class(s) you are adding...thus I removed those on the click, then simplified the code using the benefits of jQuery chaining.

$(document).ready(function() {
  $("a.project").on('click', function(event) {
    // remove old classes
    $('.moveMe').removeClass('moveMe');
    $('firstGalleryImage').removeClass('firstGalleryImage');
    // get the characters of the clicked element
    var portfolioLastTwoChars = $(event.target).attr('data-src').slice(-8, -4);
    var galleryLastTwoChars = $("img").first().addClass("firstGalleryImage").attr('data-src').slice(-8, -4);
    if (portfolioLastTwoChars === galleryLastTwoChars) {
      return;
    } else {
      $('img[alt*=' + portfolioLastTwoChars + ']').addClass("moveMe");
      $("div").children('.moveMe').not(".loaded").prependTo("div.image-list");
    }
  });
});

Now, as to the odd function getImageName() within your document ready, not sure what exactly you are attempting with that; That may actually BE your issue if you are trying to re-execute that event handler for the $("a.project").on('click', If you simply want to execute the click handler that is one thing, if NOT and you wish to attach that to some NEW elements then perhaps you need to attach it differently such as:

$(document).on('click',"a.project",function(){...

Put the $(document) on some wrapper of the a.project elements to be more efficient.

Then you can trigger that from somewhere with

$("a.project").trigger('click');

Note that trigger may need to be activated on some other element (an image?) like: (hard to guess without any markup to go by)

$("a.project").find('img').eq(0).trigger('click');