Using Javascript to refresh an image and update a class within a DIV when another DIV is clicked

I have a code that is quite lengthy to share here, so I've created a demo on JSFiddle: http://jsfiddle.net/Emily92/5b72k225/

This particular code takes a random image and divides it into multiple sections based on the class applied to the div containing the image.

Upon loading the page, a random image is chosen from an array and assigned a class. My goal is to create a separate div that, when clicked, will refresh the div housing the image. The desired outcome is to replace the current image with a new random one bearing the same class.

Currently, the only way to display a new image in the div is by refreshing the entire page. Ideally, this action should only reload the specified div without affecting other elements on the page.

I've attempted to achieve this with the help received on this platform. Specifically, lines 980-1018 of the JavaScript code in the JSFiddle represent my current endeavor. However, solving this issue appears to be more intricate due to the manipulation of the image by the JavaScript code. It might be necessary to reload both the image and the JavaScript manipulation simultaneously.

The following snippet depicts my ongoing efforts:

$(function() {
    var imageArray = [
    'http://www.webdesignhot.com/wp-content/uploads/2009/10/CatsVectorImage.jpg',
    'http://www.costume-works.com/images/halloween_cat_in_witch_hat.jpg',
    'http://onthewight.com/wp-content/2013/04/sooty-ryde.jpg'];
    reloadImages(imageArray);
    $('#reload').on('click',function(){
        $( "#masterdiv img[id^='div']" ).each(function(index){
            $(this).removeClass("jqPuzzle jqp-r"+(index+3)+"-c"+(index+3)+"-SCN");
            $(this).fadeOut( "slow", function() {
                if(index==0) {
                    reloadImages(imageArray);
                }
                $(this).addClass("jqPuzzle jqp-r"+(index+3)+"-c"+(index+3)+"-SCN");
                $(this).fadeIn();

            });
        });
    });
});


function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

function reloadImages(array){
    shuffleArray(array);
    for(var i=0;i<3;i++){
        document.getElementById('div'+(i+1)+'id').src=array[0];
    }
}

You can find additional details regarding this issue in the HTML section of the JSFiddle. Any assistance provided in resolving this matter would be greatly appreciated. Thank you in advance for your help!

Answer №1

Before the page loads, the plugin scans the images' src, collects them, and creates a puzzle from them. This means that you can't simply update the images since they won't be there anymore. To update the images, you need to clear out the divs for each difficulty level (easyDiv, mediumDiv, hardDiv), add new <img> elements under each div, and then reload or call the plugin. You can find the updated code at: http://jsfiddle.net/5b72k225/6/

Here are the changes I've implemented:

  1. I split the existing reloadImages function into separate functions - initImages and reloadImages. initImages is executed initially, while reloadImages is triggered during reloading.
  2. I introduced a new function called makePuzzle by removing the initialization of the plugin from the $(document).ready() block. This allows us to call makePuzzle after loading new images.

The revised $(document).ready() now sets up the images, adds a click event handler to the button, empties the divs when clicked, inserts new <img> elements, and calls the plugin again.

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

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

Using Jquery to gather attributes in order to assemble numerical values

I have an unordered list (ul) where each list item (li) has a 'data-pret' attribute. I need to extract the values from the li items that have the class '.selectat' and display them as a total. Example: 10 + 20 + 15 = 45 http://jsfiddl ...

Dividing the text by its position value and adding it to a fresh object

I needed to divide the paragraph into sections based on its entityRanges. Here is what the original paragraph looks like: { type: 'paragraph', depth: 1, text: 'Do you have questions or comments and do you wish to contact ABC? P ...

To access a form element in JavaScript function, utilize the dynamic form name approach

Currently, I am facing an issue with a JavaScript alert function where I am trying to view the HTML form URL before it is submitted. Following advice from a post on StackOverflow about retrieving form submit content before submit, I attempted to implement ...

Utilizing loop variables in ng-class and ng-click directive

This piece of code generates a list consisting of seven thumbnails, with the currently active image designated by the active and thumb classes. <div ng-repeat="no in [1, 2, 3, 4, 5, 6, 7]"> <img ng-src="images/{{no}}t.jpg" class="thumb" ng ...

Using the mapState function in vuex allows for easy access to Vue methods

I have an important task to complete while the data is being computed using vuex mapState. I must ensure that the vue method countAlerts is called every time the data changes; however, the computed property needs to invoke this method and unfortunately, ...

Passing Node.js MySQL query results to the next function within an async.waterfall workflow

In my node.js code using express, I have set up a route to request data from a mysql database. My goal is to pass the returned JSON in tabular form to another function to restructure it into a hierarchy type JSON. I have individually tested the script to ...

Difficulty with Line Breaks in Spans

I've noticed that my multi-line address in the footer is not breaking correctly at certain screen widths. Each line of the address is enclosed within a <span> tag with a specific class and then styled either as block or inline-block in the CSS ...

Choosing Drop Down Options Dynamically with Jquery

I have a total of 4 Drop Downs on my page. https://i.stack.imgur.com/6tHj5.png Each drop-down initially displays a "--select--" option by default. Additionally, each drop-down has a unique ID assigned to it. The second drop-down is disabled when the abov ...

Trigger a function when clicking outside the element, similar to how a Bootstrap modal is closed

I have successfully created a popup box using angular in my project. It appears when I click on an icon and disappears when I click on the close button. However, I would like it to also close if someone clicks outside of the popup. Can anyone help me with ...

SVG with complete coverage of width and height

Here's the challenge: create a full window svg image with aspect distortion without using an SVG tag. Why avoid the SVG tag? Because I plan to replace the SVG later on (possibly frequently) and haven't found a simple way to do so. Previous attem ...

The CSS on the maps infobox is not rendering properly when an icon is clicked

Hey everyone, I'm in the process of creating a travel blog on WordPress and have encountered some issues with the CSS on my site. I've included maps and tables that look fine in my fiddle, but when I transfer them to my website, they appear disto ...

I would prefer not to add another database table just to differentiate between team members and friends. Can you provide assistance with this?

Instead of creating another table named friends in Strapi and linking it to Visual Studio Code, I have opted to use a Characters table for both team members and friends. This way, I can input new data only at Characters and filter it to differentiate betwe ...

Tips for importing a different js file from an npm package without needing to include the entire node_modules path

When using the ES2016 import syntax to load the select2 library from an npm module via Webpack, everything works smoothly and the select2.js file is loaded from the node_modules directory. The node_modules directory also contains a full version of the lib ...

Implementing jQuery to trigger actions on every other click

Here we have a snippet of code that either posts and updates #arrival or removes it and replaces it with standard text. One click for posting, another click to reset. The issue is that currently it requires two clicks to do the initial posting, followed by ...

Disabling iframe javascript timers when iframe is no longer in the user's view

Currently, I am working on a blog post that will showcase various HTML5/Javascript animations through multiple <iframe> sections. These animations utilize methods such as requestAnimationFrame() and/or setInterval(). Due to limitations within the blo ...

relocate & adjust the position of an element beneath a sibling element in the HTML code

My goal is to align an <li> element with the exact same position as the preceding <li> on the webpage. I am utilizing the jQuery function .position() for this purpose. Whenever a left swipe or drag action is detected on my <li> component ...

Close button for body

I have created a form that floats in the center of the screen On this form, I have included a button designed to close it However, I would like for the form to be closed anywhere on the screen when clicked with the mouse Here is my code: $(".offer-clo ...

What's the reason for the icon not updating in the responsive mode?

I am venturing into the world of responsive web design for the first time. My aim is to create a website menu that drops down when the menu icon is clicked, using the onclick command in JavaScript. However, upon inspecting my browser, I noticed an uncaught ...

Addressing a HTML/CSS navigation bar formatting glitch

I have been attempting to replicate the design from , but with the menu positioned at the top of the screen. Despite reviewing tutorials on w3schools and other sources, I am still unable to understand why it is not aligning correctly at the top. Below is t ...