[Drupal] How to make the current image of slideshow in a page as the background of related pages?

| | 2 min read

One of our Drupal clients wanted to make the current image of the slideshow in a page as the background of other pages. It is possible to achieve this effect using a combination of jQuery and Ajax. Read on to know how to make the current image of slideshow in a page as the background of related pages in a Drupal site.

Current image of slideshow in a page can be set as background of other pages by taking the src of last viewed image, pass it through ajax request to a page using jquery where it can be stored in cookie.In pages other than the page showing slideshow the value of background can be set using jquery css property.

The value of last viewed image in slideshow can be retrived using cycle function of jquery.



  $('div containing slideshow').cycle({startingSlide: 0, before:onBefore});

In onBefore function we can get the id of the div showing the current slideshow image.URL of the image can be retrived using .attr method of jquery.This URL can be passed with ajax requests where it can be stored in cookie.



function onBefore(prev,curr,z) { 

  //Before changing slides do this

  var attrid = $(curr).attr('id'); 

  var imgsrc = $('#'+attrid+' img').attr('src');

  $.ajax({

    type: "GET",

    url: "/set_slide?slide="+imgsrc

  });

}

In the page callback function for set_slide the src is stored in cookie.



$image = $_GET['slide'];

setcookie("slideshow_image", $image);

The value from cookie can be stored in drupal.settings which can be directly accessed in jquery.

Variables can be stored in drupal.settings using drupal_add_js function.You can refer the following code for storing the variables.



$background_image = $_COOKIE['slideshow_image'];

$settings = array('index' => $background_image);

drupal_add_js(array('my_Module' => $settings), 'setting');

In juqery function the value stored in drupal.settings can be accessed by the following code:

imageUrl = Drupal.settings.MyModule.index;

Background image can be set using Jquery function.



$('myObject').css('background-image', imageUrl);

This sets the current image of slideshow as background of other page.Hope this helps.