Ways to focus on a specific div using JavaScript

I am attempting to create a 'snow' effect on the background of a particular div with a red border. Here is the code, but you can also view it here:

    <!-- language: lang-js -->

        var width = getWidth();
        var height = getHeight();
        var flakeCount = 50;
        var gravity = 0.7;
        var windSpeed = 20;
        var flakes = [];

        function getWidth() {
            var x = 0;
            if (self.innerHeight) {
                x = self.innerWidth;
            }
            else if (document.documentElement && document.documentElement.clientHeight) {
                x = document.documentElement.clientWidth;
            }
            else if (document.body) {
                x = document.body.clientWidth;
            }
            return x;
        }

        function getHeight() {
            var y = 0;
            if (self.innerHeight) {
                y = self.innerHeight;
            }
            else if (document.documentElement && document.documentElement.clientHeight) {
               y = document.documentElement.clientHeight;
            }
            else if (document.body) {
                y = document.body.clientHeight;
            }
            return y;
        }

    function getRandom(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    var currentFlake = 0;
    var snowglobe = document.getElementById("snowglobe");

    while (currentFlake < flakeCount) {
        var flake = document.createElement("div");
        flake.className = 'flake';
        flake.style.fontSize = getRandom(12, 24) + 'px';
        flake.style.top = getRandom(0, height) + 'px';
        flake.style.left = getRandom(0, width) + 'px';
        flake.innerHTML = "•";
        newFlake = snowglobe.appendChild(flake);
        newFlake.speed = getRandom(1, 100);
        flakes.push(newFlake);
        currentFlake++;
    }

    function doAnimation() {
        for (var i = 0; i < flakes.length; i++) {
            newY = parseFloat(flakes[i].style.top) + (flakes[i].speed / 100) * gravity;
            newX = false;
            // Calculate Y position
            if (newY > height) {
                newY = 0 - parseInt(flakes[i].style.fontSize);
                // If Y is at bottom, randomize X
                newX = getRandom(0, width);
            }
            // Calculate X position if it hasn't been set randomly
            if (!newX) newX = parseFloat(flakes[i].style.left) + Math.sin(newY / windSpeed);
            if (newX < -20) newX = width + 20;
            if (newX > width + 20) newX = -20;
            // Set new position
            flakes[i].style.top = newY + 'px';
            flakes[i].style.left = newX + 'px';
        }
    }
    setInterval(doAnimation, 10);

    window.onresize = function(event) {
        width = getWidth();
        height = getHeight();
    }​

<!-- language: lang-css -->

    #snowglobe .flake {
        position: absolute;
        width: 1px;
        height: 1px;
        color: rgba(255,255,255,0);
        text-shadow: 0 0 3px rgba(255,255,255,1);
    }​

<!-- language: lang-html -->

    <div class="ui-full-width">
        <div class="container even" id="snowglobe">
            <h3><span class="num">4</span>Add freshly boiled water to the pot</h3>

            <p>Give it a stir and secure the lid. Wrap your pot in a tea-cosy if it's nippy outside!</p>            
        </div>
    </div>


<!-- end snippet -->

<div class="ui-full-width">
    <div class="container even" id="snowglobe">
        <h3><span class="num">4</span>Add freshly boiled water to the pot</h3>

        <p>Give it a stir and secure the lid. Wrap your pot in a tea-cosy if it's nippy outside!</p>            
    </div>
</div>

Answer №1

There appears to be an issue with your myjs.js file, as it contains extra characters at the end when loaded in my browser, causing a script error:

SCRIPT1014: Invalid character
myjs.js (116,2)

The problematic script section is as follows:

window.onresize = function(event) {
   width = getWidth();
   height = getHeight();
}â // << here

If you're unsure of the browser being used, press F12 to access the console for JavaScript errors and other helpful information.

Upon further inspection, it seems that there are multiple stray characters at the end of your script:

window.onresize = function(event) {
    width = getWidth();
    height = getHeight();
}​ // ??

Have you made any changes to the file encoding settings that could have caused this issue?

Answer №2

Appreciate you taking a look. I've made some changes to the code and that's where the additional characters came from. The file encoding options have remained untouched.

Upon reviewing the console, it seems that there were some undefined elements. It appears that I overlooked a significant portion:

let width = getWidth();
let height = getHeight();
const flakeCount = 50;
const gravity = 0.7;
const windSpeed = 20;
const flakes = [];

All issues have been resolved now!

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

jQuery divs seem to "gaze up" towards the mouse pointer

I am attempting to recreate a fascinating effect using jQuery - where "cards" move in response to the mouse cursor as if they are looking up at it. I have come across a script that almost achieves what I need, but I require the ability to control the mov ...

What is the best way to showcase the information from this API on an HTML page using Vanilla JavaScript?

I am currently working on implementing an AJAX call to fetch data from a movie API online. Below is the HTML code I have written for this: <html> <head> <meta charset=utf-8> <title>Movie Database</title> ...

Utilize AJAX and jQuery to seamlessly upload files through the PHP API

I have code in the following format. PHP file : <form action="http://clientwebapi.com/createEvent" id="form_createEvent" method="post" enctype="multipart/form-data"> <input type="text" name="image_title" /> <input type="file" name="media" ...

Why isn't my JavaScript AJAX PHP if statement functioning properly?

I have been struggling with this issue for more than two hours now and cannot seem to find a logical solution. When I remove the If statement highlighted by --> this arrow, the alert() function works perfectly fine. It triggers when I simply use if(true ...

Minimize the gap between the input text and the lower border

Is there a way to bring the input text field and text closer together by reducing the space between the bottom border and the text? #a { padding: 1px 3px; background: transparent; border: 0; outline: 0; border-bottom: 0.8px soli ...

A linear gradient effect originating from the center/middle of the background

Is it possible to create a linear-gradient background that starts from the center or middle of the screen? This is the CSS I am currently using: body { display: table; width: 100%; height: 100%; margin: 0 auto; background-repeat: no-r ...

Creating a message sniping command with Discord.js

I'm having trouble getting my bot to log/snipe a message when someone says 'zsnipe'. I want to make 'zsnipe' a command, but it's not working. Could you let me know what I'm doing wrong? Here is the code snippet: bo ...

The value of ng-model is consistently stored as a string, regardless of whether the input is a number or

<div> <input type="text" ng-model="test"/> </div> When a value is entered into the input field with the ng-model "test", it is always treated as a String type, even if it is a valid number. However, I am looking for a way to determine th ...

Cookie Strategy for Managing Popups Site-wide

Below is a script that will trigger a popup after 60 seconds of page load. This script also creates a cookie to prevent the popup from appearing more than once. The cookie expires when the user's session ends. However, the popup only appears on the e ...

Troubleshooting an Angular.js "Hello World" application that is malfunctioning

I've been trying to get a simple Hello World app working by following different tutorials, but it doesn't seem to be functioning correctly. I've double-checked my code and everything looks right to me. Could someone please assist me in troub ...

How to stop Accordion from automatically collapsing when clicking on AccordionDetails in Material-UI

I am working on a React web project with two identical menus. To achieve this, I created a component for the menu and rendered it twice in the App component. For the menu design, I opted to use the Material UI Accordion. However, I encountered an issue wh ...

The power of PHP's echo function comes alive as it seamlessly connects

I am currently working on developing a product catalog using PHP. Below is the HTML flex-container code: <div class="products"> <?php echo file_get_contents("http://192.168.64.2/CodeWay/Pages/product.php"); ?> & ...

if a condition is not being properly assessed

Currently, I am working on a $.ajax call to retrieve data in JSON format. Within this JSON data, there is an element called "status." My code snippet checks if the value of `data.status` is equal to "success" and performs some actions accordingly. Despite ...

Is there a way to set up an automatic pop-up for this?

Experience this code function AutoPopup() { setTimeout(function () { document.getElementById('ac-wrapper').style.display = "block"; }, 5000); } #ac-wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; back ...

Utilize jQuery ajax to pull in data from an external website

I've been doing some research on using jQuery ajax to extract links from an external website, but I'm a bit lost on where to begin. I'm taking on this challenge just to push my skills and see what I can accomplish. While reading about the S ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Unattractive destructuring during conditional assignment

When working with object properties, ESLint often suggests using object destructuring. However, this can sometimes result in redundant lines of code. ESLint may not allow something like the following (which might seem like the preferable approach): const ...

Getting the Mongoose Model using Express parameters is a simple process

Is it possible to dynamically fetch a mongoose model based on the req.params.model? Check out this example of a Schema const mongoose = require("mongoose"); const Schema = mongoose.Schema; const SmartSchema = new Schema({ SmartPriority: { type: Stri ...

Reordering the stacking order of Grid Items in material-ui

I'm facing an issue with the stacking order of grid items when the browser shrinks. On a regular desktop screen (lg): --------------------------------------------- | col 1 | col 2 | col 3 | --------------------------------------- ...

React virtual list module: Scrolling down through code commands

In my React Grid with Virtual Scrolling, I am facing a challenge with the lack of a "scroll to row feature." At times, I need to select a specific row programmatically and ensure that it is displayed to the user. Although I have the ID of the desired row ...