Randomly swap images in HTML when a button is clicked

In order to change images randomly on mouse click, I came across this solution:

<SCRIPT LANGUAGE="Javascript">
function banner() { } ; b = new banner() ; n = 0
b[n++]= "<A HREF='index.html'><IMG SRC='images/pic1.jpg'></A>"
b[n++]= "<A HREF='index.html'><IMG SRC='images/pic2.jpg'></A>"
b[n++]= "<A HREF='index.html'><IMG SRC='images/pic3.jpg'></A>"
b[n++]= "<A HREF='index.html'><IMG SRC='images/pic4.jpg'></A>"
i=Math.floor(Math.random() * n) ; 
document.write( b[i] )
</SCRIPT>

Although this method works well, I want "pic1" to always stay as the first picture (even when refreshing the page), and I also do not want "pic1" to be included in the selection of other pictures that change randomly on mouse click.

Thank you, Aviv

Answer №1

Recently, I implemented this feature in a project where the initial slide remains consistent.

http://example.com/jsfiddle/8HsAc/4/ Click on Change Order multiple times to witness the transition between second and third images.

<button class="shuffle-order">Change Sequence!</button>

<ul>
    <li class="panel current">
        <img src="http://placeholder.com/250x250" />
    </li>
    <li class="panel current">
        <img src="http://placeholder.com/350x250" />
    </li>
    <li class="panel current">
        <img src="http://placeholder.com/450x250" />
    </li>                
</ul>


$(document).ready(function() {
    // Reorder slides excluding the first one
    $('.sequence').click(function(e) {
        $('ul').each(function(){
            var $ul = $(this);
            var $liArr = $ul.children('li:not(:first)');

            // randomly shuffle list items within current ul
            $liArr.sort(function(a,b){
                var temp = parseInt( Math.random()*10 );
                var isOddOrEven = temp%2;
                var isPosOrNeg = temp>5 ? 1 : -1;
                return( isOddOrEven*isPosOrNeg );
            })
            // append shuffled list items back to ul
            .appendTo($ul);            
        }); 
    });
});

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

Eliminate the AM and PM options from the input time selection dropdown menu in HTML

I'm looking to eliminate the AM / PM option in this time input dropdown, can it be done? The form builder currently uses 24-hour format based on the presence of the AM / PM field. ...

"Struggling to make the 'overflow: hidden' property work for an absolutely positioned

I'm struggling to conceal an absolutely positioned image within a CSS grid layout. Below is the code snippet: HTML: <div class="relative-parent"> <div v-for="item in 12" class="hiding-parent"> <div c ...

Scrolling triggers events

I am currently working on getting code to execute when the scroll bar reaches a certain point on my page, specifically halfway down the page or at 500px. The challenge I'm facing is that the code works fine for triggering the event when scrolling to t ...

I'm having trouble getting the float left to work properly in my HTML/CSS code

Currently, I am diving into the world of HTML / CSS on my own. After following some tutorials, I have taken the leap to work on my very first project. My goal is to layout three images and three text elements on a single page using CSS. The desired struct ...

Value of an object passed as a parameter in a function

I am trying to use jQuery to change the color of a link, but I keep getting an error when trying to reference the object. Here is my HTML : <a onmouseover="loclink(this);return false;" href="locations.html" title="Locations" class="nav-link align_nav" ...

Choosing a row in a table with ASP.NET by utilizing jQuery on click

After setting up a table in ASP.NET with the feature to select individual rows using a link at the end of each row, I have been able to successfully implement it. The process involves setting a value at the top of the view and then dynamically changing the ...

Floating a div while scrolling down until the footer is reached

I have a requirement to float a <div> while scrolling down, and it should stop when the <div> reaches the footer. Similarly, it should move back up when scrolling up. I managed to achieve this functionality using the following code: if (window ...

Is using tables still considered a recommended practice for organizing a layout such as the one shown in the [IMG]?

Looking for recommendations on arranging images in the footer, in line with the design mockup using HTML/CSS. Wondering if tables are still a viable option for this purpose? ...

Modify the size of the text in an <iframe> using inline css

After attempting the command below, I noticed that the text size within the iframe remained unchanged. Is there a different method to adjust it? <iframe id="myiframe" src="**" height="230px" scrolling="no" style ...

The $_REQUEST variable is functioning properly, while the $_POST variable seems to

I currently have an HTML form using the post method. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type='text/javascript& ...

What is the best way to determine which button was clicked in Django?

My HTML has two buttons - one for accepting and the other for rejecting requests. I am trying to figure out how to determine which button was pressed along with the email of the applicant (tutor_application.tutor.chalkslateuser.email). Despite multiple a ...

Using jQuery to animate one widget with the login widget

EDITED : I have decided to switch from jQuery to PHP for my WordPress sidebar issue. Please refer to this link for more details: Add echo to my wordpress sidebar for non-connected users I am using the Nice Login Widget plugin on my test WordPress website. ...

The CSS selector "not:nth-child" is failing to function properly within the template

Trying to apply a margin-top to all labels except the first one in a row using the :not() and :nth-child selectors. Having trouble with my selector, can anyone help? .form-group:not(:nth-child(1)) + .label { margin-top: 20px; } <div class="form- ...

What is the best way to ensure email address validation is done perfectly every time?

Can someone assist me with validating email addresses correctly? I am able to handle empty fields, but now I need a way to identify and display an error message for invalid email addresses. How can I modify my validation process to check for improper email ...

Utilizing Backbone script for fetching data from an external JSON source

I am seeking assistance on how to utilize a Backbone script to display data from a JSON file. Here is the structure of the HTML Page: <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</tit ...

Align the text characters vertically within a word or sentence

I currently have a logo that consists of lines and text. I would like to create a similar version using CSS for my website. My goal is to have the letters "T - S o N" appear in one line with the letter "o" positioned vertically centered between the "S" an ...

"Placing the save button on top of a div - a step

I am trying to position a div with an ID below a save button in my HTML code. The current setup looks like this: <button id="item_new" data-action="create" class="floating-button mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button- ...

Ajax encountered a problem while attempting to download the file

I have a situation where JavaScript generates content within a function, and I need to save that content in my downloads folder. However, when I attempt to do so via AJAX, it does not work and no errors are being displayed. Here is the JS code: $.ajax({ ...

Issues with implementing @font-face on a singular font

I've encountered an issue while setting up a website for a client concerning the fonts. Most fonts are displaying correctly, but there is one font, "chunkfive", that is not working as expected. The problem becomes more severe in Internet Explorer wher ...

Tips for organizing and sorting date data in a JSON datatable

I am working with two date input fields: <form id="refresh" method="post" action="income.php"> <input type="text" id="dari" name="dari" /> <input type="text" id="sampai" name="sampai" /> <button type="submit">Refresh</b ...