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

Issue with Bootstrap table not identifying rows created with AJAX calls

Just to provide some context: I am currently utilizing Bootstrap-table with Bootstrap version 3.3.6 My objective is to populate a table using AJAX and jQuery, but I'm encountering an issue where none of the bootstrap extensions seem to function proper ...

Access Information within live tabs

When attempting to click on any tabs in order to retrieve their respective data, I am successfully able to do so. However, I'm only able to retrieve the data of one row at a time. Can anyone provide assistance with this issue? <div class="col-lg-1 ...

Deactivate a button when clicked on a card that has been mapped

After creating a card component and mapping through each card, I added an onClick function to disable the button of the clicked card. However, my logic ended up disabling all buttons instead. Here is the code snippet where I define the rendering of the UI ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

What is the best way to format and return a result object list in JavaScript or Angular?

I have a question regarding the use of for loops in JavaScript or utilizing Angular to output the resulting object list. Here is an example of an object list: var alist = []; alist = [ { 'code': 1000, 'type': 'C' ...

The issue of jQuery not loading within Ajax content has been resolved

Appreciate the assistance provided. I am facing an issue where my jQuery code does not load within ajax content. Below is the code snippet from index.html : <script language="javascript" type="text/javascript"> $(function() { $("#gps").load("find. ...

What is the best technology to implement for a band website design?

I'm in the process of creating a website for my friend's band, and I need some creative input. The site will feature minimal content such as a bio, news, and embedded audio/visual material. While my web development skills are decent, I'm loo ...

Creating a button in HTML that performs a POST request without redirecting involves using specific code techniques

Looking for a way to create an HTML button that triggers a POST request to a quick route with parameters passed through req.params. The challenge is preventing the button from redirecting me to the route when clicked, but instead staying on the same page w ...

Setting a static width for a specific cell in HTML5 - What's the best way to go about it?

When working with HTML5, how do I define a specific width for a table cell? Many of the <col> properties that were present in HTML4 are no longer applicable in HTML5. Just to clarify, I am aware that I can use <td style="width:150px">, but thi ...

Enable the duplication of strings within an array

Below is the HTML code snippet I am working with: <div class="col-sm-8"> <div class="row col-sm-12 pull-right paddingDiv"> <div class="col-sm-12"> <div class="marginBottom pull-right"> <bu ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

What is the best way to display two columns in each row using Angular?

Can you please provide guidance on how to display two columns in each row using Angular? I am attempting to showcase only two columns per row, and if there are more than four items, I want to display them on an ion-slide. Further details will be provided. ...

Using Javascript, print the port number to the console

I am currently developing a small Electron app with node.js and I am facing an issue with outputting the port my application is connected to for development purposes. Below is my MySQL connection code snippet: const mysql = require('mysql'); c ...

JQuery Validation appears to be failing to validate

Having some trouble with the JQuery validator plugin in my Rails app. It's not displaying any errors or validating anything. Can't seem to figure out what's wrong with my code. Any assistance would be greatly appreciated! $(document).ready( ...

Allow access only to authorized staff members in Django

So I'm working on this Django code and I want to display a button only if the user is either a super user or staff. I've tried using is_superuser and is_staff but it's not working for me. {% if request.user == post.user %} <div class=&qu ...

Generate a new perspective by incorporating two distinct arrays

I have two arrays containing class information. The first array includes classId and className: classes = [ {classid : 1 , classname:"class1"},{classid : 2 , classname:"class2"},{classid : 3 , classname:"class3"}] The secon ...

Can JQuery's 'unslider' be customized to only change the backgrounds?

Check out my source at this link: http://codepen.io/anon/pen/Bvkjx Observe how the content and background images rotate correctly. Now, I'm curious if it's feasible to keep the following content static <p>SOME CONTENT1</p> while ...

Need help making switch buttons in react-native?

Using the library found at this link has been quite successful on my iPhone, but it does not display properly on Android. It appears as shown here. ...

Guide to vertically aligning text in an overlay using CSS within Angular 2

I currently have an overlay on my page that displays a spinner (an Angular material component) and accompanying text. This overlay covers the entire page and prevents clicking on elements below it. The spinner is positioned in the center of the page, and ...

Trouble with document updates in MongoDB/Mongoose causing a delay?

I am currently working on updating an object nested in an array in my application. When I test this functionality using Postman, I am experiencing a delay that requires me to make two requests in order to see the updated value. if (taskStatus) { cons ...