d
Topic
Posts:
2
August 20, 2007

Random image Javascript This post is outdated

Hi there, I'm quite new to Javascript and even newer to Shopify so here goes!.... I simply need to call up a random image on refresh on my page.theme using javascript. These will be illustrative images (hard coded, I guess), rather than (dynamic) product images. I've done this on a standard HTML page before but I know I'm doing something wrong when it comes to liquid templates. At the moment I've linked to {{ 'randomimage.js' | asset_url | script_tag }} in the <head> tag of theme.liquid, which contains the following:



<script language="JavaScript">

var theImages = new Array() 

theImages[0] = '{{'page_image_01.jpg' | asset_url}}'
theImages[1] = '{{'page_image_02.jpg' | asset_url}}'
theImages[2] = '{{'page_image_03.jpg' | asset_url}}'


var j = 0
var p = theImages.length;

var preBuffer = new Array()
for (i = 0; i < p; i++){
   preBuffer[i] = new Image()
   preBuffer[i].src = theImages[i]
}

var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write(+{{'theImages[whichImage]' | asset_url}}+);
}


</script>

And on page.liquid I've added:
<script language="JavaScript">
<!--showImage();//-->
</script>
to call up the js function in the right place. _But_ I know somewhere I'm going really wrong, either on the js file itself (where i reference the images) or the the page template (do I need to enclose the script in special characters?)... I know the solution is probably very obvious I'm really stuck here! I'd be very grateful for any help. Thanks, Sian
http://www.sianjones.net http://maddialexander.myshopify.com
i
Replies
danW Shopify Advisor
Posts:
1037
Last edited August 20, 2007

I think you need to call it with window onload.


<script language="javascript">
<!--
window.onload = showimage();
//-->
</script>

You can check out this thread from a while back to make sure you javascript is correct.

http://forums.shopify.com/categories/2/posts/10722

Dan - http://www.xtremechargers.com
Posts:
150
August 20, 2007

I don’t think you can embed liquid into a .js file like that.

If you want to use that, it would be better to put the script into one of the liquid templates.

Matt Beck, CouldBe Studios | Portland, OR | http://www.couldbestudios.com : http://deals.couldbestudios.com
danW Shopify Advisor
Posts:
1037
August 20, 2007

That’s correct Matt.

I use this code to randomly show a customer feedback quote and all the code is inline in theme.liquid.

Dan - http://www.xtremechargers.com
SillySyl Member
Posts:
8
Last edited August 22, 2007

In other words, Siad is doing it incorrectly? I’m confused. I am trying to do the same as Siad without luck. If I cannot embed liquid into a .js file, then my .js file should look like this?

// JavaScript Document
var theImages = new Array()

//Random-loading images
theImages[0] = 'home_rotator1.jpg' // replace with names of images
theImages[1] = 'home_rotator2.jpg' // replace with names of images
theImages[2] = 'home_rotator3.jpg' // replace with names of images

var p = theImages.length;
var preBuffer = new Array()

for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));

function showImage(){
if(whichImage==0){
document.write('<a href ="/"><img src="'+theImages[whichImage]+'" border=5 width=363 height=260></a>');
}
else if(whichImage==1){
document.write('<a href ="/"><img src="'+theImages[whichImage]+'" border=0 width=363 height=260></a>');
}
else if(whichImage==2){
document.write('<a href ="/"><img src="'+theImages[whichImage]+'" border=0 width=363 height=260></a>');
}

}

Is this correct so far?

And then I added DanW’s “showimage” code to the header div in the theme.liquid file. I’ve checked the previous post and the code looks the same.

Unfortunately, it doesn’t work. If anyone has any suggestions, please let me know?

Thanks,

Posts:
150
August 22, 2007

What you want to do is drop the .js file, and put your functionality (with the liquid tags) into the header of your theme.liquid file as an inline script.

Matt Beck, CouldBe Studios | Portland, OR | http://www.couldbestudios.com : http://deals.couldbestudios.com
danW Shopify Advisor
Posts:
1037
Last edited August 23, 2007

Try it like this. All inline where you want the image to show


<div id="randimage">
<a href=/"><img src="{{ 'default.jpg' | asset_url }}" /></a>

<script type="text/javascript">

   var imageCount = 3;

   function get_random() { 
      var ranNum= Math.floor(Math.random()* imageCount );
      return ranNum;
   }

   window.onload = function() {
      var whichImage=get_random();
      var image=new Array(imageCount)
         image[0] = "<a href=\"/\"><img src=\"{{ 'default.jpg' | asset_url }}\" /></a>";
         image[1] = "<a href=\"/\"><img src=\"{{ 'alternate1.jpg' | asset_url }}\" /></a>";
         image[2] = "<a href=\"/\"><img src=\"{{ 'alternate2.jpg' | asset_url }}\" /></a>";

      $('randimage').innerHTML = image[whichImage];
    }

</script>
</div>

Dan - http://www.xtremechargers.com
SillySyl Member
Posts:
8
Last edited August 22, 2007

Hi Dan,

I copied and pasted all your code and put it into the proper places but it still doesn’t work. I renamed the images to match your names and I added the default-image to the randimage div.

Here are my calls to the javascript files:


    {{ 'layout.css'    | asset_url | stylesheet_tag }}
    {{ 'mootools.js' | asset_url | script_tag }}
        {{ 'slimbox.js' | asset_url | script_tag }}
        {{ 'random.js' | asset_url | script_tag }}
    {{ content_for_header }}

and here is the code that I put where the image is suppose to show:

    <div  id="logo">
        <!-- Display Random Image -->
       <div id="randimage">
           <a href="/"><img src="{{ 'default.jpg' | asset_url }}"/></a>
       </div><!-- end random image -->
    </div><!--end of logo -->        

Can you see anything incorrect here? I’ve been trying all kinds of things included trying to make it all inline but nothings working, and I really appreciate everyones help.

danW Shopify Advisor
Posts:
1037
Last edited August 23, 2007

Ok. I took a deeper look and the code I posted was way off. I used my test store and came up with the correct solution.

I couldn’t get it to work by calling it from a js file so I just put it inline. Works like a charm.

If you renamed your images to mimick my previous code, then you should be able to just copy and paste this in place of your randimage div tag and it should work.

I updated my post above with the updated code so no one would try use the old code.

Dan - http://www.xtremechargers.com
Posts:
2
August 23, 2007

Well it works for me – I think we can consider this case solved, MacGyver! And no duct tape in sight…

Thank you danW and Matt.

Sian

http://www.sianjones.net http://maddialexander.myshopify.com
SillySyl Member
Posts:
8
August 24, 2007

Copy, paste, refresh, and it works beautifully. Thanks guys for your help.

Posts:
6
September 19, 2007

I could get your code to work no problem, but what I need is to randomly change out a background image. I can’t seem to get this working. Help! This is what I have:

<div id="randimage">

<script type="text/javascript">

   var imageCount = 3;

   function get_random() { 
      var ranNum= Math.floor(Math.random()* imageCount );
      return ranNum;
   }

   window.onload = function() {
      var whichImage=get_random();

      var image=new Array(imageCount)
         image[0] = "<img src=\"{{ 'bg_1.jpg' | asset_url }}\" />";
         image[1] = "<img src=\"{{ 'bg_2.jpg' | asset_url }}\" />";
         image[2] = "<img src=\"{{ 'bg_3.jpg' | asset_url }}\" />";

    var bgimage=image[whichImage];

      $('randimage').style.backgroundimage = "url('" + bgimage + "')";
    }

</script>

danW Shopify Advisor
Posts:
1037
Last edited September 20, 2007

try this

var image=new Array(imageCount)
         image[0] = "{{ 'bg_1.jpg' | asset_url }}";
         image[1] = "{{ 'bg_2.jpg' | asset_url }}";
         image[2] = "{{ 'bg_3.jpg' | asset_url }}";

var bgimage=image[whichImage];

$('randimage').style.background-image = "url(bgimage)";

or

$('randimage').background = bgimage;

Dan - http://www.xtremechargers.com
Posts:
6
September 21, 2007

Nope, still no joy.
I also tried this

 var image=new Array(imageCount)
         image[0] = "url('{{ 'bg_1.jpg' | asset_url }}' )";
         image[1] = "url('{{ 'bg_2.jpg' | asset_url }}' )";
         image[2] = "url('{{ 'bg_3.jpg' | asset_url }}' )";

    var bgimage=image[whichImage];

      $('randimage').style.background-image = bgimage;

but that didn’t work either. Any more ideas?

Posts:
6
September 21, 2007

Also.. maybe I should mention, I plan to change out the background image for the <body> of the page. I was hoping once I got the div working, it would also work giving the <body> tag the same id.

danW Shopify Advisor
Posts:
1037
September 27, 2007

Sorry nadia I don’t. My javascript kung fu isn’t all that good. :(

Dan - http://www.xtremechargers.com
Posts:
339
Last edited September 27, 2007

Hey Nadia

I may be way off here, depending on your desired outcome, but you might be able to butcher this script from A List Apart which allows you to switch between alternate stylesheets.

It should be relatively straightforward to assign 3 css sheets (each of which only specify the body bg image) as possible ‘alternate’ stylesheets and load them in after your main css in the head. Then write a little js function called when the page loads which picks one of the bg stylesheets at random.

If you want the bg image to randomise on every page, you wouldn’t even have to worry about cookies.

Is that worth looking into?
M

Mike www.cardiaconline.co.uk | www.anothervision.co.uk
Posts:
6
September 28, 2007

Thankyou!! It was worth looking into .. and it worked!

I took out all the cookie stuff in the stylesheetswitcher.js, and replaced the window.onload with my get_random function. Worked perfectly.

I think I may be linking to the alternate stylesheets in a messy way – I have hard-coded the links because I didn’t know how to call an alternate stylesheet tag.

{{ 'binkie.css'     | asset_url | stylesheet_tag }}

<link rel="alternate stylesheet" type="text/css" href="/files/shops/random_number/assets/binkie_1.css" title="bg1" />
<link rel="alternate stylesheet" type="text/css" href="/files/shops/random_number/assets/binkie_2.css"  title="bg2" />
<link rel="alternate stylesheet" type="text/css" href="/files/shops/random_number/assets/binkie_3.css"  title="bg3" />

But oh well, as long as it works!

Posts:
339
Last edited September 28, 2007

Great! glad it worked. I’ve used the technique to switch stylesheets on browser resize, so I was pretty hopeful.

You should be able to use asset_url, which would be a little more future-proof if JP switch their servers around in the future:

<link rel="alternate stylesheet" type="text/css" href="{{ 'binkie_1.css' | asset_url }}"  title="bg1" />
<link rel="alternate stylesheet" type="text/css" href="{{ 'binkie_2.css' | asset_url }}"  title="bg2" />
<link rel="alternate stylesheet" type="text/css" href="{{ 'binkie_3.css' | asset_url }}"  title="bg3" />
Mike www.cardiaconline.co.uk | www.anothervision.co.uk
Posts:
1
May 26, 2010

You guys are doing what i'm looking for. But i want my main banner on my website to change with a link to the product that is featured. Also i know some js files can make it  so you can choose up to 4 things to look at up front.

izac01 Member
Posts:
3
Last edited April 29, 2011

 

<div id="randimage">
<a href=/"><img src="{{ 'default.jpg' | asset_url }}" /></a>

<script type="text/javascript">

   var imageCount = 3;

   function get_random() { 
      var ranNum= Math.floor(Math.random()* imageCount );
      return ranNum;
   }

   window.onload = function() {
      var whichImage=get_random();
      var image=new Array(imageCount)
         image[0] = "<a href=\"/\"><img src=\"{{ 'default.jpg' | asset_url }}\" /></a>";
         image[1] = "<a href=\"/\"><img src=\"{{ 'alternate1.jpg' | asset_url }}\" /></a>";
         image[2] = "<a href=\"/\"><img src=\"{{ 'alternate2.jpg' | asset_url }}\" /></a>";

      $('randimage').innerHTML = image[whichImage];
    }

</script>
</div>

Having some trouble with the above code

Im very new to this stuff so apologise in advance.

I have copied and pasted the code into the page I want the random image. However only the default image is coming up. I cannot get it to change on refresh. 

Tried multiple browsers and definitely have javascript on.

 

 

THanks

 

 

 

Subpixel Member
Posts:
1
Last edited August 01, 2011

Same problem here. Aside from the fact that the jQuery selection should be

$('#randimage')

I can't see what's wrong.

Only the default image loads. Help?

 

Posts:
31
Last edited October 07, 2011

I had trouble with the above code too so I tooled around with it a little bit and found a working solution. Place this snippet in one of your .liquid files. For instance, I put this in the index.liquid file.

<script type="text/javascript">
   var imageCount = 11;
   $(function(){ 
      var whichImage=get_random();
      var image=new Array(imageCount)
        image[0] = "<img src=\"{{ 'image-1.png' | asset_url }}\" />";
        image[1] = "<img src=\"{{ 'image-2.png' | asset_url }}\" />";
        image[2] = "<img src=\"{{ 'image-3.png' | asset_url }}\" />";
        image[3] = "<img src=\"{{ 'image-4.png' | asset_url }}\" />";
        image[4] = "<img src=\"{{ 'image-5.png' | asset_url }}\" />";
        image[5] = "<img src=\"{{ 'image-6.png' | asset_url }}\" />";
        image[6] = "<img src=\"{{ 'image-7.png' | asset_url }}\" />";
        image[7] = "<img src=\"{{ 'image-8.png' | asset_url }}\" />";
        image[8] = "<img src=\"{{ 'image-9.png' | asset_url }}\" />";
        image[9] = "<img src=\"{{ 'image-10.png' | asset_url }}\" />";
        image[10] = "<img src=\"{{ 'image-11.png' | asset_url }}\" />";
        function get_random() { 
           var ranNum= Math.floor(Math.random()* imageCount );
           return ranNum;
        }
        $('#randimage p a').prepend(image[whichImage]);
    });
</script>

 

Then where ever you want the image, you can place this code below there, but make sure it is in the same template.

<div id="randimage"><p><a href="interactivejohn.com"></a></p></div>

Worked like a charm for me! Thanks Dan for the base idea in this thread.

John Dahl | http://interactivejohn.com/

Log in or sign up for an account to reply.

This thread has been closed! You will not be able to reply.