How to get the image by ID from image Slider and store it to the cookies?

790 views Asked by At

I have an Image slider of 5 pics in Home page in a asp.net MVC application. Now when user will click on other menu tab within the application the last seen image of the image slider should be stored in cookies. so when the user come back to the homepage,image slider will start from the last seen image . My chtml:

 <div id="sliderFrame">
    <div id="slider"> 
    <a id="image1" href='#' class='linkdisabled'>
    <img src="~/content/Internal/Images/image1.jpg" alt="" />
    </a>
    <a id="image2" href='#' class='linkdisabled'>
    <img src="~/content/Internal/Images/image2.jpg" alt="" />
    </a>
.....

I am thinking of overwriting images by ID in cookies and when user get back to homepage last stored image in the cookies will be shown in the image slide. But how to get the image id and store it into cookies? Please help.

1

There are 1 answers

2
El cero On

First, get the container of links and the collection of links inside this container

var slider = document.getElementById("slider");
var links = slider.getElementsByTagName("a");

Next, initialize a method to set a cookie

function setCookie(){
    document.cookie="lastSeenImageId=" + this.id;
}

Add event listeners to each link. Note: in this example, I do not consider the support of Internet Explorer < 9, because I do not know whether you use jQuery or your own methods for cross-browser compatibility:

for(var i=0; i<links.length; i++){

    links[i].addEventListener("click", setCookie, false);

    /*(function(j){
        links[j].attachEvent("onclick", function(){
            setCookie.call(links[j]);
        });
    })(i);*/

}

Last, fire a click event when a page is loaded

function fireAnEvent(){

    var cookie = document.cookie;

    if(cookie && document.cookie.test(/lastSeenImageId=([^;]+)/)){
        var link = document.getElementById(RegExp.$1);
        link.click();    
    }

}

window.addEventListener("load", fireAnEvent, false);
// window.attachEvent("load", fireAnEvent);

This code is just an example, and may require some correction, according to your needs.