In order to display the particle-slider logo effect, the JavaScript on the page needs to be refreshed

I have a website frontend integrated from WordPress using an HTML 5 Blank Child Theme. The site features a logo effect utilizing particle slider for screen sizes greater than 960px, and a flat logo image for screen sizes less than 960px. Everything works perfectly; however, when I resize between logos, the page needs to be manually refreshed (by pressing cmd+r) before the particle slider effect reappears. How can I fix this so that the effect automatically shows after resizing?

Below is the code snippet -

particle-slider.php

<?php /* Template Name: particle-slider */ ?>
<!-- particle-slider template -->

    <div id="particle-slider">
        <div class="slides">
            <div class="slide" data-src="<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logohight.png"></div>
        </div>
        <canvas class="draw" style="width: 100%; height: 100%;"></canvas>
     </div>
     <script type="text/javascript">
        var ps = new ParticleSlider({ 'width':'1400', 'height': '600' });
     </script>
  <div id="logo"> <img src="<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logo.png"> </div>

  <!-- particle-slider template -->

style.css

/* RWD for logo */

@media screen and (max-width: 960px) {


    #particle-slider {
        display: none;
    }   

...

}

ps.js

// Particle Slider version goes here
 ...
 // Code continues as shown in original text
 ...
;

Answer №1

Summary:

To simplify and enhance your code, replace the existing script with the updated one below:

<script type="text/javascript">
// DOM ready function to ensure proper query
document.addEventListener('DOMContentLoaded', function() {
    var ps, timeout;
    handlePS();
    window.addEventListener('resize', function() {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(handlePS, 250);
    });

    function handlePS() {
        if (document.body.clientWidth >= 960) {
            if (window.ps && typeof ps !== null) {
                ps.init(); 
            } else {
                ps = new ParticleSlider({
                    'width': '1400', 
                    'height': '600'
                });
            }
        }
        else {
            ps = null;
        }
    }
});
</script>

Explanation: Optimizing Resize Event Handling

This updated code snippet improves handling of the resize event by calling the init() method based on the current window width. It also organizes code creation into a separate function for better structure, utilizing a variable ps for tracking instance status.

Furthermore, you can enhance this setup by invoking the function when the page loads and during resize events:

handlePS();
window.addEventListener('resize', handlePS);
  • An enhanced approach waits for DOM readiness and debounce effects via setTimeout.
  • It includes logic to trigger the init() method only after a brief delay post-resize using a timer.

Incorporate jQuery for further streamlined coding:

Instead of:

window.addEventListener('resize', handlePS);

Use:

$(window).on('resize', handlePS);

Replace document.body.clientWidth with $(document).width() for simplicity.

Additional Update:

For experimentation, I utilized an image from the provided comment in the revised sample page at this link. The demo features paired-down Particle Slider code integrated with the specified image on another page. Note that there remains a minor flashing issue during resizing events.

Answer №2

Latest Update

The issue that was encountered seems to stem from the fact that when you hide the div used by ParticleSlider for drawing, it results in a Canvas with dimensions of 0x0. This then triggers an exception within the drawParticles method, which is called by the nextFrame function. It's important to note that ParticleSlider is designed so that after the initial call made from the constructor, nextFrame utilizes requestAnimationFrame to schedule itself. Other methods like nextSlide</code or <code>resize only alter data without restarting the animation sequence. Therefore, the exception in the initial call halts the animation, and the solution involves explicitly calling nextFrame.

To address this, you can modify the nextFrame function to monitor success/failure and invoke it from the resize handler if necessary. Here's some sample code:

var ps = new ParticleSlider({ 'width': '1400', 'height': '600' });

// Modify nextFrame to track failure/success
var nextFrameCalled = false;
ps.oldNextFrame = ps.nextFrame;
ps.nextFrame = function () {
    try {
        ps.oldNextFrame.apply(this, arguments);
        nextFrameCalled = true;
    } catch (e) {
        console.log(e);
        nextFrameCalled = false;
    }
};

var addEvent = function (object, type, callback) {
    if (object.addEventListener) {
        object.addEventListener(type, callback, false);
    } else if (object.attachEvent) {
        object.attachEvent("on" + type, callback);
    } else {
        object["on" + type] = callback;
    }
};
var oldWidth = window.innerWidth;
addEvent(window, 'resize', function () {
    var newWidth = window.innerWidth;
    if (newWidth >= 960 && oldWidth < 960) {
        console.log("Restarting particle slider " + newWidth);
        ps.resize();
        if (!nextFrameCalled)
            ps.nextFrame();  // force restart animation
        else {
            nextFrameCalled = false;
            setTimeout(function () {
                if (!nextFrameCalled)
                    ps.nextFrame();  // force restart animation
            }, 100);
        }
    }
    oldWidth = newWidth;
});

A live demo showcasing this implementation is available on this plunker. Open the demo in a separate window and adjust the size within 2 seconds to simulate different conditions.

Prior Solution Overview

If you're encountering issues with particles not re-shuffling upon window size change beyond 960px, consider incorporating code similar to this (utilizing jQuery):

var ps = new ParticleSlider({ 'width': '1400', 'height': '600' });

var oldWidth = $(window).width();
$(window).resize(function () {
    var newWidth = $(window).width();
    if (newWidth >= 960 && oldWidth < 960)
        ps.resize(); // Initiate reshuffling of particles via init()
    oldWidth = newWidth;
});

You can also achieve similar functionality without jQuery as demonstrated in this Stack Overflow response.

Answer №3

If you want to exert greater authority over the ParticleSlider function, consider utilizing the resize feature in conjunction with jquery smart resize.

You can declare a new ParticleSlider with specific width and height values:
var ps = new ParticleSlider({ 'width': '1400', 'height': '600' });

Then, listen for window resizing events using "debouncedresize" from jQuery Smart Resize plugin, and trigger the resize method of ParticleSlider accordingly:
$(window).on("debouncedresize", function( event ) {
    ps.resize();
});

Answer №4

The issue at hand is as follows: The slider is being drawn into the canvas using JavaScript, but it appears that the script is only loaded once when the page initially loads. While the authors claim that the slider should be responsive on their site, in reality it is only being resized and not replayed when the window is resized.

My suggestion is to try calling

ps.nextSlide(0);

inside a $(window).resize() event handler. This will reload the current slide!

If this approach does not work, you can attempt to reload the entire slider using either the init() function or the loadingStep() function. (Unfortunately, the documentation is somewhat unclear to me in certain areas.)

For example:

$(window).resize(function(){
    ps.nextSlide(0);
});

You can find information about the available functions here:

Answer №5

There are two significant issues with your current use case:

  • If the Particles are initialized before the target is visible, the image size becomes invalid (0x0)
  • Even after resizing the resolution smaller while the Animation is running, it continues to run in the background

In order to address both problems, I have included the following script:

var ps = null

function init(){
  var isVisible = window.innerWidth >= 960;
  if (!ps && isVisible) {
    // create and initialize
    ps = new ParticleSlider({
      ptlGap: 1,
      ptlSize: 1,
      width: 1e9,
      height: 100,
    });

    ps.init(false);
  } else if (ps && !isVisible) {
    // stop and remove
    ps.requestAnimationFrame = function() {}; // Stop render loop
    ps = null;
  }
}

window.addEventListener('load', init, false)
window.onload = init;
window.addEventListener('resize', init, false);
window.onresize = init;
html, body {
  background-color: black;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  color: #fff;
  text-align: center;
}

.slides, & > .dg {
  display: none;
}

.low-res {
  display: none;
}

@media screen and (max-width: 959px) {
  .draw {
    display: none;
  }

  .low-res {
    display: inline;
    width: 50%;
  }
}
<html>
  <head>
    <meta name="viewport" content="width=device-width" />
    <title>ParticleSlider</title>
    <script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/23500/ps-0.9.js"></script>
  </head>
  <body id="particle-slider">
    <div class="slides">
      <div id="first-slide" class="slide" data-src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGkAAAAgCAMAAAAmC6asAAAAMFBMVEX19vf19vft7u/19vfp6uv19vfx8vP19vf19vf19vf19vfm5+j19vcAAAD19vfl5udu+MchAAAADnRSTlOIVcIz10StZneZEewiAMEzGswAAAF/SURBVHja7ZXZbsQwCEXjneXa/P/fFntm0uRpVGkaqVX8YAW4cMCxkq1ftW7STbpJP1sJb0lFPkJiekuq4TMkfkti+gxpe0uivRmB9LQOlHraNixnYErPONAfcYZntYfv9aDtJTmUO5OCeukGR5paqZtbGaSVzYWIlZ9DI6vVpC6shJw5TzdlZk47qZpldAkteBVToxNJrLGqoil6MPE9A1bSNorUXPYWvbLUjbg37lwRNPYW6x6eJK4ilB2hVmChJw2nWx4He3Map1exMVFvQyMVN78rlexbY7Gk0tWUm7gsHUnikQ6dwzLRLM/tRKIlGMMFoijmpthqBocLFTLWO41GnhrFXZIGTiTz5pIyA9G4uqSeSV3W4bSsqvycg0x9RTpcKHaHHybNOZBXfPa41jNjLCeqjRopzgI4kXYcsDqVZWJaZwVWHpYBTOuoACCvEpjTC3DFd6/oVV9YmPw+CWsb+H1SxVWkkgkoV5B6ijasXnMjBPIf/u436e+TvgDCaqPX6lO5yQAAAABJRU5ErkJggg==">
      </div>
    </div>
    <canvas class="draw"></canvas>
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/23500/codepen-white.png" class="low-res"/>
  </body>
</html>

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

Original: full size responsive background images without stretchRewritten: high-quality

I have incorporated the Full page scroll feature for a website from GitHub user peachananr. You can find it here: https://github.com/peachananr/onepage-scroll My goal is to assign a resizable background image to each "page". I am using the CSS rule ' ...

Struggling with finding the appropriate CSS selector?

I'm struggling to find the correct selector. Let me do my best to explain the situation: I am currently working on a project where I am unable to make changes to the HTML and JavaScript due to dynamic content and other constraints. Within this proj ...

Decide whether a ListBox item in ASP.NET has been chosen by leveraging the power of jQuery

I have the following unique jQuery function that will loop through all the elements of my ASP.NET ListBox. It is triggered when clicked: $('#<%=MyListBox.ClientID %>').children("option").each(function () { } The functionality of this fun ...

Check for my variable in the redux state before proceeding

Currently, I am creating connection and registration screens, with a profile button on the bottom tab bar. The objective is for the user to be directed to their profile page if they are logged in (user data stored in Redux), or to a landing screen with log ...

Implementing a feature in ReactJS that allows users to upload multiple images in base64 format

I'm trying to develop an image uploader using base64 and I want the output as an array. However, I am encountering an issue where the array is coming out empty!. I suspect it might be due to an asynchronous problem. Any tips on how to incorporate asyn ...

CSS/HTML - Issue with nested divs not displaying properly

Attached is an image that provides context for the issue I'm facing. https://i.stack.imgur.com/nQXh8.jpg I'm encountering difficulties with styling a nested div element. When double-clicking the text within this div, only half of it gets highlig ...

Cannot assign border to an undefined element - JavaScript

Currently, I am attempting to validate some code using javascript. However, I am encountering a frustrating issue where I keep getting an "Uncaught TypeError: Cannot set property 'border' of undefined". Being relatively new to javascript, I ...

Discover the process for breaking down JSON data into separate stages using the Express API

My API architecture is causing a problem as I try to insert it into an array called items[]. https://i.stack.imgur.com/qe802.png The setup involves a simple API built on express + mongodb. The challenge lies in figuring out how to store data from the pos ...

The gap separating the three columns in the DIVs structure

Here is an example that I need The images are being loaded from a MySQL while loop, and I want the spacing between them to be such that the left column and right column touch each side with the middle image centered. Just like in the picture :D This is m ...

What is the best way to rotate a cube when it is clicked on?

My current project involves rotating a cube by clicking on buttons either on the cube itself or floating next to it. At the moment, I have them floating for easier testing purposes, but placing them directly on the cube is not an issue. The main issue I&a ...

Is there a way to modify the value of a JavaScript object?

My React componentwillmount fetches data from an ExpressJS API using Axios and receives a JSON response, which is then converted to an object by Axios. [{"client_nick":"PlayTalk","connected_time_record":183710127},{"client_nick":"PlayTalk","connected_time ...

Ways to retrieve a value from the column within the editor's template of a Kendo.Grid when it loses focus or onblur()?

I'm working with a grid that has an editor template in my HTML setup. Whenever I click on a column, it switches to edit mode, enabling me to modify the value in the textbox. My specific query is, how can I retrieve the value of $50.00 using jQuery up ...

The data structure '{ variableName: string; }' cannot be directly assigned to a variable of type 'string'

When I see this error, it seems to make perfect sense based on what I am reading. However, the reason why I am getting it is still unclear to me. In the following example, myOtherVariable is a string and variableName should be too... Or at least that&apos ...

Stop the slider when a video pops up

Years ago, I had a slider created for me that supports both images and video with a timer. However, the issue I'm facing is that when the timer runs every 10 seconds, the video gets cut off if it's not finished playing. Below is the json file st ...

Expanding/Combining entities

I'm facing an issue while trying to Extend/Push/Merge an object using AngularJS. The problem arises when I attempt to extend the object, as it adds a new object with an Index of 0 and subsequent additions also receive the same index of 0. //Original ...

adjusting the value for a chosen selection

I'm facing an issue with certain selects within a class. Whenever the change event occurs on any of those selects, I need to search all the selects for the selected value where the change event happened and then swap the two values. Let me illustrate ...

I need help establishing a distinct GMT end time for the classyCountdown.js plugin

Regarding the jquery countdown plugin found at this link, The current trigger code only sets a target end time based on the page load, and I am looking to set it relative to a specific GMT/UTC date and time. $('.countdown').ClassyCountdown({ ...

Adding a value to an element in JavaScript to interact with it using Selenium

After implementing the provided code snippet, I noticed that it replaces the value in the element with a new one. However, I am looking to append or insert a new line rather than just replacing the existing value. Is there an alternative command like app ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

Graphic selectors: a new take on radio buttons

I've been attempting to make this work, but it's not functioning correctly. Below is the CSS code: .input_hidden { position: absolute; left: -9999px; } .selected { background-color: #000000; } #carte label { display: inline-bl ...