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

Tips for submitting a jQuery star rating:

I recently installed and added a plugin to one of my pages that transforms radio buttons into stars. While the form control works perfectly, I am facing an issue with submitting the form. The radio buttons are grouped together as stars but they do not subm ...

Filtering multiple rows in a table using Javascript

I'm currently working on creating a filter that can filter based on multiple inputs, with each input filtering in a separate column. Here is the JavaScript & code I am using: function myFunction(column, input) { var filter, table, tr, td, i, t ...

How can I insert an empty option following a selected value in a dropdown menu using jQuery?

How to use jQuery to insert a blank option after an existing option? I attempted to add a blank option, but it ended up at the top of the dropdown. I actually need one existing option followed by one blank option. For example: <option></option& ...

Is It Best to Override Behavior in a Directive?

Having two directives that display lists of documents, one for user-favorited documents and the other for user-pinned documents. The criteria for displaying these documents depend on the values of "pinned" and "favorite" within each document object: docum ...

Issue with jquery .click function not triggering after CSS adjustment

In the process of creating a fun game where two players take turns drawing on a grid by clicking <td> elements. Currently, I have implemented the functionality to toggle the background color of a <td> element from black to white and vice versa ...

Problem with using puppeteer to interact with a dropdown menu

I have a project in which I am utilizing puppeteer to create a bot that can automatically check for my college homework assignments. The problem I am encountering is that when the bot tries to click on a dropdown menu, it fails and I receive an error messa ...

Troubleshooting: Images not displaying on webpage due to Ajax, JQuery, and JavaScript integration

I'm currently working on building a dynamic photo gallery using Ajax and JQuery in Javascript. I have set up a directory named "images" in Visual Studio Code and it contains my selection of 5 images. However, when I click the "next" and "previous" but ...

I aim to utilize vanilla JavaScript in order to remove the parent element of the button being clicked when the user interacts with it

My latest project involves a meme generator that allows users to input text and images, which are then combined to create a unique 'meme'. Each meme is assigned a unique ID and features buttons for deleting the meme upon hovering. To achieve this ...

Creating an animated time-based scrollable bar chart in javascript

As someone who is new to JavaScript and charting, I am seeking assistance with a specific task. Despite browsing various JavaScript charting libraries and examples, none seem to address my issue: My goal is to generate dynamic stacked bar charts, as depic ...

Switch classes while navigating within a div

My website has a sticky sidebar with a list of cars and their corresponding categories in a table: <ul class = "cars"> <li class=""><a href="javascript:void(0)" class="model" data-id="1"> BMW </a></li> ...... ...

Discovering the world of Promises in TypeScript and understanding how to return specific types

Transitioning from coding in Clojure for the past two years to TypeScript has been an interesting journey. However, I've hit a bit of a roadblock today. The issue lies with my interface: interface ICustomer { id: number, first_name: string } I ...

Retrieve the response status using a promise

There is a promise in my code that sometimes results in an error response (either 400 or 403, depending on the user). I am trying to handle this situation by catching the response and implementing a conditional logic to execute different functions based on ...

Modifying specific attributes of an object within the $scope: A step-by-step guide

When working with Angular, if you have code in the view that looks like this: <span ng-model="foo.bar1"></span> <span ng-model="foo.bar2"></span> <span ng-model="foo.bar3"></span> Due to how Angular maps objects, you c ...

Why is my data attribute not being updated by the jQuery.data() method?

Here is an example of HTML code: <div id="mydiv" data-hoo-foo="bar"></div> As illustrated above, I am attempting to achieve the following: var $mydiv = $('#mydiv'); $mydiv.data('hoo-foo'); // returns 'bar&apos ...

Tips on skipping the need to repeatedly use `@ApiProperty()` for every dto in NestJs-swagger

I'm currently exploring ways to streamline the process of specifying @ApiProperty() for each DTO. I've heard about a method involving the creation of a nest-cli.json file, where if you define Promise<DTO> in your controller within nest-swa ...

iterate through the ordered list (ol) elements within nested lists

I am currently attempting to convert my hierarchical list into a JSON object in the following format; [ {title: title1,id: 1,children: [ {title: title1_1,id: 1_1,children: [ {title: title1_1_1,id: 1_1_1,children: []}, ...

PHP: Bootstrap CSS for Carousels

I'm experiencing some difficulties with the Bootstrap CSS Carousel on my website. The left and right arrows seem to be unresponsive, and the slides are not transitioning automatically. I have been unable to identify the root cause of this issue. Belo ...

Creating multi-level nested lists with numbering using HTML and CSS

Is there a way to create a unique numbering format using only HTML and CSS lists (<ul> or <ol>)? 1. Item A 2. Item B 3. Item C 3.1. Subitem C.1 3.2. Subitem C.2 3.3. Subitem C.3 4. Item D 4.1. Subitem D.1 4.1.1 Sub-subi ...

Removing a specific item from a Kendo UI dropdown list

Recently, I encountered a predicament with a dropdownlist populated from a datasource. Following a certain event, my goal is to eliminate a single item from the dropdownlist identified by id = 22. Although I recognize this may not be the best practice du ...

Utilizing ES6 imports with module names instead of paths

Is there a way to import modules using just their name without the full path? For instance, can I simply use: import ViewportChecker from 'viewport-checker'; instead of import ViewportChecker from '../ViewportChecker'; I'd ...