Random image Javascript

by Beardedbaglady - Member - 01:04PM, Aug 20, 2007

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

danW

Shopify Advisor

03:38PM, Aug 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

Matt Beck

Shopify Advisor

06:17PM, Aug 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

danW

Shopify Advisor

09:01PM, Aug 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

SillySyl

Member

12:35AM, Aug 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,

Matt Beck

Shopify Advisor

06:10AM, Aug 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

danW

Shopify Advisor

04:38PM, Aug 22, 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

SillySyl

Member

11:02PM, Aug 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

01:55AM, Aug 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

Beardedbaglady

Member

04:23PM, Aug 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

SillySyl

Member

02:32PM, Aug 24, 2007

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

nadia

Member

05:44AM, Sep 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

08:14PM, Sep 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

nadia

Member

04:42AM, Sep 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?

nadia

Member

04:50AM, Sep 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

01:23PM, Sep 27, 2007

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

---

Dan

lorem ipsum

Member

02:48PM, Sep 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

nadia

Member

12:38AM, Sep 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!

lorem ipsum

Member

12:28PM, Sep 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" />

You must login to post a comment!

Don't have an account yet? Sign up for one.