Is it possible to dynamically change the background image of my website every time a new link or URL is clicked?

There are countless questions online about this topic, but many of them involve languages like PHP, ASP, and JQUERY. I, on the other hand, am only familiar with CSS and Java Script. Can someone provide me with code examples in these languages for my question?

I'm also interested in having a background on my website that changes with every refresh!

Thank you in advance!

Update: I was able to find sample code that works perfectly!

Credits to this forum:

<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function changeImg(imgNumber)   {
var myImages = ["Background/Background.jpg", "Background/Background2.jpg", "Background/Background3.jpg", "Background/Background4.jpg", "Background/Background5", "Background/Background6", "Background/Background7"];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
</script>
<style type="text/css">
.bg {background-attachment:fixed; background-repeat: no-repeat; background-position:top right;}
</style>
</head>
<body class="bg">
<p>Some text</p>
<!-- put a lot text lines here to see that the background stays fixed. -->
<p>Some text</p>
</body>
</html>

Answer №1

Here are some creative solutions:

Organize all files neatly in a single folder.

  1. Create a database table with indexed images and use a random number generator to display a corresponding image.

  2. Rename images in the folder sequentially and add a randomized number for uniqueness.

After selecting a random image, easily update background or other DOM elements using JavaScript like this:

document.querySelector('body').style.backgroundImage = 'url('+<your image>+')';

You can also achieve this with jQuery for added simplicity.

Answer №2

One way to accomplish this task is by utilizing JQuery. Simply create a click event for each link on the page.

$(function(){
    $("link1").click(function(){
        $("body").css({background-image:"url('link1_image.gif')"}); 
    });
});​

If you want to display a random image every time the page is refreshed, you can use the onload function to set a random background image.

$(function(){        
    var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
    $('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
});​

Give it a try and hopefully everything will work as expected. Thank you!

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

magnetic container: stationary container nested within absolutely positioned container

I recently created a page that can be viewed here: [LINK] This page is set up to scroll horizontally, resulting in a row of divs with black borders. However, I am facing an issue with the smaller divs inside (red ones). I want them to stay within the par ...

Stop the Decimal in MUI TextField

Having trouble creating a customized Currency Input? You may be experiencing an issue where the textfield prevents the input of decimals. Take a look at the code below for possible solutions. main.ts const [_val, setVal] = React.useState(""); const h ...

Using JavaScript and HTML to show the current month, date, and year on a webpage

I am looking to display not only the time, but also the month, date and year. My attempted solution involved creating variables for the month, day and year, and then using getElementById. Here is an example of what I tried: var d = date.getDay(); var mn ...

What is the process for customizing the appearance of a prop within the <TextField> component?

Using my custom DatePicker.js component, I have two instances of <TextField>. When the user clicks on the <CalendarIcon> within the <TextField>, a small calendar pops up. However, I want to style the label in the <TextField> in a sp ...

Calculate the remaining days, hours, and minutes until a set date using JavaScript

My script is supposed to count the days, hours, and minutes from the current time until May 8 at 23:59:59, but it seems to be missing 2 days and 1 hour. As of March 23 at 10:37, there should be 48 days, 13 hours, and 23 minutes left, but my clock is showin ...

Error Encountered: Element Type Mismatch in Root Div

In my quest to locate the root div element, I have implemented the following method: var parentDoc = window; while (parentDoc !== parentDoc.parent) { parentDoc = parentDoc.parent; } parentDoc = parentDoc.document; var divContent = parentDoc.getElement ...

Encountering a limitation when trying to send multiple parameters in a PHP onclick

I am attempting to pass multiple parameters in an onclick using variables, but I keep encountering this error: Uncaught SyntaxError: missing ) after argument list. The issue seems to be with this specific line of code: echo'<a onclick="cha ...

send the user to a different page while transferring post data using Javascript

Currently, I have an HTML form that utilizes the post method to send data to a PHP page for processing into a MySQL database. However, before the user submits the form, there is a button that allows them to view a PDF of the entered data on a new page. Whi ...

Arranging buttons and input forms for mobile screen sizes with Bootstrap styling

My challenge lies in aligning a text input with three buttons on the same line, especially on smaller screen sizes. The code snippet I have is: <div class = "container" <input type="text" class = "form-control" placeholder="Input here"> & ...

Having difficulty retrieving precise HTML information for data scraping purposes

I'm a beginner in python and exploring web scraping for a project on . Currently, I'm using selenium to automate the search for a CUSIP and then extract specific details about it. Although I've successfully automated navigation from EMMA&a ...

The functionality in the React Native code that uploads images to an S3 bucket is currently failing to initiate the network request

I have been using a redux-observable epic to upload images to my AWS S3 bucket through react-native-aws3. It has been functioning smoothly for quite some time. However, recently it seems to have stopped entering the .map and .catch blocks of code. I suspec ...

Enhance your website with unique and custom fonts using

I am utilizing this repository. How can I incorporate custom fonts into my project? I have created a folder named "fonts" within the assets directory and placed my fonts there. fonts.scss @font-face { font-family: 'Lato'; src: url('../ ...

Nodejs client application for maintaining constant communication with an echo server

As someone who is just starting out in the world of nodejs, I recently managed to create an echo server using tutorials from YouTube. While there's nothing wrong with my server code, I am now facing the challenge of developing a client program that ca ...

Angular Material Select without underline not specified

I'm currently utilizing Angular Material for my project. My task involves creating a custom component that includes a md-select component. However, I'm facing an issue where the md-select component needs to have no underline, similar to a workaro ...

Is there a way to utilize Javascript to submit a PDF form?

Can JavaScript be used to reference a Form or Button on a PDF document? I am attempting to write JavaScript code that will either submit a form or click a specific button that submits the form. The challenge I am facing is knowing how to reference the but ...

When `rxjs` repeat and async pipe are applied and then removed from the DOM, the resulting value becomes null

One of the classes I have is responsible for managing a timer. It contains an observable that looks like this: merge( this._start$, this._pause$ ) .pipe( switchMap(val => (val ? interval(1000) : EMPTY)), map( ...

Jquery Tab navigation arrows for scrolling pages

As a beginner in jQuery and JavaScript, I am struggling to create a scroll tab menu. You can view my example tabs on JSFiddle here. My objective is to only show 5 tabs at a time and hide the rest. The user should be able to click on side arrows to reveal t ...

Enhancing the Canvas with JavaScript: Implementing 2048

In my high school computer science class, my partner and I chose to create a unique version of the game 2048 for our final project. Instead of traditional moving tiles, we are implementing a grid with properties like number and color assigned to each til ...

"Learn the technique of animating SVG paths with JavaScript, a step beyond traditional HTML filling

I am looking to animate SVG path elements with JavaScript instead of HTML. I have come across numerous articles discussing how to achieve this through JavaScript and jQuery by manipulating the attributes. Some helpful links I found: Fill color SVG path w ...

Implementing Material-UI Autocomplete: How to Include a Starting Value for the startAdornment

I am using autocomplete with multiple selection permission. https://codesandbox.io/s/bold-jackson-dkjmb?file=/src/App.js In the provided example, there are 3 options for cities. How can I manually insert a value in TextField that is automatically selected ...