1

Having trouble changing an image in Squarespace. I'm getting very close but I have not yet solved the problem.

I am trying to generate a random number, use that number to pick a photograph from my pictures array and replace the background of my gallery with that image.

My jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
 $(document).ready( function() { 
    const index = randomMove(0, pictures.length),
    picture = pictures[index];

   // Gets the img tag under the imageWrapper class
   const test = $('.imageWrapper > img');
   // Gets the first index of the div (the image I want to manipulate)
   const test1 = test[0];
   // trying to change the picture
   // I have tried attr('src', picture) as well and did not work
   const test2 = $(test1).data("currentSrc", picture);
 })

 const randomMove = (mi, ma) => {
  const min = Math.ceil(mi),
    max = Math.floor(ma),
    selection = Math.floor(Math.random() * (max - min) + min);

  return selection;
};

  const pictures = [
    "https://i.imgur.com/bsG8hx7.jpg",
    "https://i.imgur.com/Vuw28Lq.jpg",
    "https://i.imgur.com/09Cfuks.jpg",
    "https://i.imgur.com/3TRmorT.jpg",
    "https://i.imgur.com/JElBKPO.jpg",
    "https://i.imgur.com/eSTVz8D.jpg",
    "https://i.imgur.com/3n1z9uc.jpg",
    "https://i.imgur.com/aW5HWI5.jpg",
    "https://i.imgur.com/5uEtErN.jpg",
    "https://i.imgur.com/HMHehUy.jpg"
  ];
 </script>

I believe the biggest challenge with this problem is that the HTML uses "data-src" and "data-image" in contrast to just a "src". This also may not be the correct way to solve this problem.

Here is my error log: https://image.prntscr.com/image/JaArgLTOT0WHY0oCkVdPCA.png

Here is the HTML code that showcases the aforementioned data-src and data-image attributes: https://image.prntscr.com/image/n1ME_XpXShifytEOfFVV8w.png

Chasen Bettinger
  • 7,194
  • 2
  • 14
  • 30
  • FYI: you shouldn't use es6 (const, arrow functions, etc) in a script tag if you want cross-browser compatibility – Tyler Sep 08 '17 at 20:17
  • Thanks for the information. I changed my code. – Chasen Bettinger Sep 08 '17 at 20:18
  • In what are you trying to load your image? if it's a background image, why you don't try `$(test1).css(.css('background-image', 'url(' + imageUrl + ')');` as per this question : [Setting background-image using jQuery CSS property](https://stackoverflow.com/questions/512054/setting-background-image-using-jquery-css-property) – DIEGO CARRASCAL Sep 08 '17 at 20:31
  • @DIEGOCARRASCAL This does not work because there is no background-image CSS property for that selector. The image is loaded through HTML. I tried your suggestion verbatim and nothing changed. Thank you for the suggestion though. – Chasen Bettinger Sep 08 '17 at 20:35
  • 1
    @ChasenBettinger Please post a [mcve] that includes the minimal amount of HTML involved. `data-src` and `data-image` attributes are not enough to go by until we know what they belong to and what values they could have (although I can take an educated guess as what value `data-src` should be) – zer00ne Sep 08 '17 at 21:00
  • @zer00ne I apologize for not being clear enough. I have commented on your solution and provided images that showcase the code that is relative to the "data-src" and "data-image" selectors. – Chasen Bettinger Sep 08 '17 at 21:03
  • 1
    @ChasenBettinger duly noted, sir. See comment at my answer. Note, I deleted second comment, so refresh the page just in case, Also, FYi – zer00ne Sep 08 '17 at 21:23

1 Answers1

1

Update

Commented 3 alternative jQuery statements that should help to manipulate a Squaresoft image (untested since I don't have a Squaresoft site)


You can dereference your jQuery Object to make it a plain object...

$('.imageWrapper img')[0].src

...and use simple properties like .src to manipulate the values.

Ref: Fisher-Yates Shuffle

See comments in demo for details

Demo

$(function() {
  const pictures = [
    "https://i.imgur.com/bsG8hx7.jpg",
    "https://i.imgur.com/Vuw28Lq.jpg",
    "https://i.imgur.com/09Cfuks.jpg",
    "https://i.imgur.com/3TRmorT.jpg",
    "https://i.imgur.com/JElBKPO.jpg",
    "https://i.imgur.com/eSTVz8D.jpg",
    "https://i.imgur.com/3n1z9uc.jpg",
    "https://i.imgur.com/aW5HWI5.jpg",
    "https://i.imgur.com/5uEtErN.jpg",
    "https://i.imgur.com/HMHehUy.jpg"
  ];

  // Callback function pass an array
  function changeImg(array) {

    // Pass the array to shuffle function get result
    var url = shuffle(array);

    /* Asign the result to src attribute of img
    || Note: the bracket notation [0]
    || this dereferences the jQuery Object, thus
    || changing it into a plain object
    || Once a plain object, simple properties
    || such as .src may be used.
    */
    $('.imageWrapper img')[0].src = url;

    // This is the equivelant in jQuery
    // $('.imageWrapper img').attr('src', url);

    /* Solution for Squaresoft images */
    /* This should work granted that the array pictures has
    || the appropriate urls pointing to images uploaded to
    || the site.
    */
    /* ALT 1. All attributes grouped
       $('.imageWrapper img').attr({
         'src': url+'?format=1500w',
         'data-src': url,
         'data-image': url
       });
    */
    /* ALT 2. attr() and .data() chained
       $('.imageWrapper img').att('src', url+'?format=1500w').data({'src': url, 'image':url});
    */
    /* ALT 3. Dereferenced jQObj and plain JavaScript
       $('.imageWrapper img')[0].src = url+'?format=1500w';
       $('.imageWrapper img')[0].setAttribute('data-src', url);
       $('.imageWrapper img')[0].setAttribute('data-image', url);
    */
  }


  // Fisher-Yates Shuffle 
  // https://stackoverflow.com/a/962890/2813224
  function shuffle(array) {
    var i = 0,
      j = 0,
      temp = null;

    for (i = array.length - 1; i > 0; i -= 1) {
      j = Math.floor(Math.random() * (i + 1))
      temp = array[i]
      array[i] = array[j]
      array[j] = temp
    }
    return array[j];
  }

  // Added for demo purposes
  $('button').on('click', function() {
    changeImg(pictures);
  });

});
<button>Change Image</button>
<section class='imageWrapper'>
  <img src='https://i.imgur.com/bsG8hx7.jpg'>
</section>






<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • Thank you for helping me with this. It is not working and it might be because of the comments I included just recently. Here is my log: https://image.prntscr.com/image/JaArgLTOT0WHY0oCkVdPCA.png And here is the html: https://image.prntscr.com/image/n1ME_XpXShifytEOfFVV8w.png – Chasen Bettinger Sep 08 '17 at 20:57
  • @ChasenBettinger Ok, that explains alot. You need to upload each image to your site, make note of each new url pointing to said uploads. Then use my modified functions. The modifications being: `$('.imageWrapper img').attr({'data-src': url,'src': url+'?format=1500w','data-image':url})`. Also the array `pictures` must be changed to reflect the new uploads – zer00ne Sep 08 '17 at 21:10
  • @ChasenBettinger FYI squaresoft is doing some heavy duty image management so you should upload images to your site and take advantage of it, forget about external images (disregard if the use of imgur is for demo purposes and you upload images normally) – zer00ne Sep 08 '17 at 21:30
  • Damn, I cannot thank you enough. I was using imgur because that's what I'm most familiar with and was even more unfamiliar with src-data. I took so long to respond because I was trying to manipulate the classes out of curiosity. Again, thank you. I have learned something exceptionally helpful today because of you! :) – Chasen Bettinger Sep 08 '17 at 21:54
  • 1
    My pleasure happy coding, sir. BTW `data-src` is probably used for "lazyloading" which is a technique of giving the browser a small amount of images to load quickly then progressively load the remaining images as the user scrolls thereby giving the browser time to uplaod smaller loads quickly. – zer00ne Sep 08 '17 at 21:55