Rotate background image upon each visit

I have a collection of around 50 background images that I want to display randomly each time a user visits my website. The idea is to provide a unique background image for every visit, without saving any information about which image was previously displayed.

Once the user closes their browser and returns or visits at a later time, a new random background image should be presented. I am unsure if this functionality can be achieved using C#, JavaScript, JQuery, or CSS.

EDIT: My web application is built using ASP.net 4.0 C#. Thank you!

Answer №1

To enhance performance and minimize bandwidth usage, avoid using cookies as noted in the comments. Instead, consider utilizing local storage within the browser to store information about the last image used. By incrementing this value at the start of a new session, you can easily display the next image.

Personally, I have had success utilizing jStorage in my projects for similar purposes.

You can save details such as the current image being shown and possibly a session ID in the user's browser storage. Subsequently, you may monitor changes in the session ID to switch to a different image accordingly.

var image = $.jStorage.get("image", 0);
var session_id = $.jStorage.get("session", "insert current session id here");

if(session_id !== "current session id")
{
   image = (image < 50) ? 0 : image+1;
   $.jStorage.set("image",image);
   $.jStorage.set("session","current session id");
}

// utilize the 'image' variable to set the background

UPDATE:

For improved efficiency, refrain from embedding this JavaScript code directly in every web page. Opt for placing it on an ASP.NET page that serves as a Javascript content type, allowing you to load it through the page's header section. This approach ensures that browser caching does not interfere with the script when the session undergoes changes.

Answer №2

Keep your website visitors engaged by storing a random selection in their session. This way, each time they return to your site, they'll see something new!

Here's an example using C#:

public string GetBackground(HttpSessionState session) {
    string bg = (string)session["session.randomBG"];
    if (bg == null) {
        // Choose a random background and save it.
        bg = "chosen background";
        session["session.randomBG"] = bg;
    }
    return bg;
}

I hope this explanation is useful for you!

Answer №3

let imageList = [
    "/pictures01.png",
    "/pictures02.png",
 ...
];

/*set background image*/ = imageList[Math.floor(Math.random()*imageList.length];

Answer №4

Absolutely, it is very feasible. Let me illustrate how this can be achieved using pseudo-code. Examples in Java will likely follow soon.

At the start of each page:

StartSession()
If ! SessionVariable[myBackground] then
    x=Randomize 50
    SessionVariable[myBackground]="image0" + x + ".jpg"
endif

<style>
body {background-image:url(SessionVariable[myBackground];}
</style>

Remember to incorporate the style tag appropriately. The user-created SessionVariable[myBackground] should be utilized. In PHP, the syntax would resemble:

$_SESSION['myBackground']

Warm regards,

Answer №5

Give this code a try:

/** 
 * Function to change the background image every hour.
 * Ensure your images are named as 0.jpg, 1.jpg, ..., 49.jpg.
 */
function updateBackground() {
  var expirationTime = 3600000,
      totalImages = 50,
      randomSeed = Math.round(Date.now() / expirationTime % totalImages);
  return '/path/to/background/' + randomSeed + '.jpg';
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am facing an issue where the auto-generated jQuery click event is not functioning as expected

Appending the table row in a different way: $('#selectStudents').append("<tr><td>"+rollno+"</td>\n\ <td>"+name+"</td>\n\ <td><a href='#' class='att-time-btn toggl ...

Contents of the container are not displayed in a single line

What could be causing the first element not to align with the other elements in the container? I'm having trouble figuring out why this is happening. The code snippet seems to work, but when I implement it on the webpage, the alignment issue arises. W ...

The JQuery video player's full screen toggle feature is not correctly assigning the class name

I've been tackling a bug in my JavaScript/jQuery video player that has left me stumped. One of the key features of this player is an enter/exit full-screen button located at the bottom of the HTML snippet: (function($) { /* Helper functions */ ...

When utilizing jQuery to add a <li> element, it suddenly vanishes

? http://jsfiddle.net/AGinther/Ysq4a/ I'm encountering an issue where, upon submitting input, a list item should be created with the content from the text field. Strangely, it briefly appears on my website but not on the fiddle, and no text is appen ...

Is it possible to use jQuery to set a value for a form control within an Angular component?

I'm currently working on an Angular 5 UI project. In one of my component templates, I have a text area where I'm attempting to set a value from the component.ts file using jQuery. However, for some reason, it's not working. Any suggestions o ...

Eliminate any vacant areas within a container and shift the container, along with its contents, on the webpage

I want to eliminate the empty space within the container while maintaining some spacing around the black box, and ensure responsiveness. Additionally, how can I shift the container with its content downwards and to the right of the webpage, while still ke ...

What is the best way to develop an expanding line animation from this starting point?

I have a vision for an animation where, upon hovering over an icon, it enlarges, increases in opacity, and reveals some accompanying text. The visual effect I am aiming for involves two lines of color expanding horizontally from the center outwards before ...

Interact with jQuery to trigger events upon clicking on a list item, excluding checkboxes within the list

I'm in the process of developing a straightforward web application. I have a dynamically generated list on one section: Subsequently, I set up an event that triggers when any element within the list is clicked: $(document).on('click', &apo ...

Tips for adjusting the width of the box-shadow in CSS

I am facing a challenge with my button that has a box-shadow effect on hover. Currently, I am unsure how to adjust the width of the box-shadow effect. Here is a snapshot of my button's current appearance: https://i.stack.imgur.com/Mg0df.png</p&g ...

Discovering the art of integrating RSS feed with GAE database

Is there any game library that can accomplish this task? I believe jQuery may also be able to achieve this, is that correct? Thank you ...

What are the differences between using the open prop and conditionally rendering a Material-UI Modal component?

Is there a difference in using the open prop or conditionally rendering Material-UI's Modal component and its built components? The closing transition may be lost, but are there any performance advantages when dealing with multiple Modals? Example wi ...

Guide to iterating through a JSON object

Initially, I expected a simple question but it's proving to be more challenging than I thought. To provide some context, there is a JSON string returned from the server located within data.occupation. {"occupation": "Boxer", "id": 2},{"occupation": " ...

Error code 1 encountered an internal error while trying to execute a task

Currently, I have this job set up to clear out unnecessary records. The code provided has been simplified for debugging purposes. However, almost 80% of the time when running it, it fails to find anything due to Error code 1 "internal error": Parse.Cloud. ...

AntiforgeryToken validation issue when using Ajax in ASP.NET MVC

When looking at this View: @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" })) { @Html.AntiForgeryToken() <div id='calendar'></div> <script src="~/Scripts/Services/Agenda.js" ...

Navigate the speech bubble tail by moving or rotating it with your mouse

For my project, I am working on creating a dynamic speech bubble that can be dragged around the corner of the bubble with the mouse. The goal is for the tip of the speech bubble to rotate automatically based on its position. Below is a snippet of my code: ...

Struggling to figure out the method for obtaining css selectors for scraping in scrapy

Struggling with scraping a website and figuring out how css selectors work in Scrapy. The css in question: https://ibb.co/eJeZpb Here are some standard css selectors: .css-truncate-target .message .js-navigation-open time-ago For scrapy, you would need ...

What is the best way to create a stylish outward curve effect for an active sidebar item using just CSS

After spending a week learning frontend designs, I attempted to replicate a design from Dribble. However, I've been struggling with recreating the active style on the sidebar due to the outward curve. If anyone could provide guidance on achieving thi ...

Avoiding the triggering of jQuery events from child elements

Here is the code snippet I am working with: <html> <head> <script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"> </script> </head> <body> <div id=&q ...

Creating an App on Shopify

After working on Shopify development for a little bit, I have encountered a specific requirement from my client that is not currently available in the app store. The task involves: Creating two discount tiers based on the total value of the cart (e.g. 1 ...

The functionality of switching between two layouts using a JavaScript button is currently not functioning

My concept involves implementing a switch that alternates between displaying a bootstrap carousel and cards. Essentially, one of them will be visible when the button is pressed while the other remains invisible. Initially, I am attempting to hide my existi ...