What is the best way to apply a class for styling my JavaScript code in CSS? I'm having trouble getting classList

I am having trouble adding a class to my JavaScript script in order to animate the images created in JavaScript to fall off the page. I have tried using the code

element.classList.add("mystyle");
, but every time I insert it, my JavaScript stops working.

The only way I have managed to style the JavaScript images is by using *img { in CSS, which is not an ideal solution.

Here is the code used in my HTML:

  <script>


    var myPix = new Array("/img/portfolio/tiket.jpg","/img/portfolio/30day.jpg", "/img/portfolio/board.jpg", "/img/portfolio/cyanotype.jpg,""/img/portfolio/dissent.jpg,", "/img/portfolio/geoapp.jpg", "/img/portfolio/jailbreak.jpg,""/img/portfolio/gtr.jpg,", "/img/portfolio/eid.jpg")   

        document.addEventListener("click", showCoords);
        
        function showCoords(event)
        {
            
        var randomNum = Math.floor(Math.random() * myPix.length); 
        var yourImage = document.createElement("img");
        yourImage.src = myPix[randomNum] ;
        
        
        yourImage.style.cssText = " border-radius: 20px; box-shadow: 0px 0px 10px 0 rgba(0, 0, 0, 0.3); z-index: -2; width:360px;height:auto;position:fixed;top:" + event.clientY + "px;left:" + event.clientX + "px;";
        
        document.body.appendChild(yourImage);
        
        }

        jQuery.fn.reverse = [].reverse;


</script>

This code randomly places images wherever the user clicks on the screen.

Answer №1

If you include the class, it will function correctly. Feel free to test it out with the interactive demonstration below. Does this meet your requirements?

var myPix = ["https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png", "https://cdn4.iconfinder.com/data/icons/social-media-2210/24/Whatsapp-128.png", "https://cdn4.iconfinder.com/data/icons/social-media-2210/24/Instagram-128.png", "https://cdn4.iconfinder.com/data/icons/social-media-2210/24/Youtube-128.png", "https://cdn4.iconfinder.com/data/icons/social-media-2210/24/Facebook-128.png", "https://cdn4.iconfinder.com/data/icons/social-media-2210/24/Twitter-128.png", "https://cdn4.iconfinder.com/data/icons/social-media-2210/24/Dribbble-128.png"];

document.addEventListener("click", showCoords);

function showCoords(event) {
  var randomNum = Math.floor(Math.random() * myPix.length);
  var yourImage = document.createElement("img");
  yourImage.src = myPix[randomNum];
  yourImage.classList.add('mystyle');

  yourImage.style.left = event.clientX + "px";
  yourImage.style.top = event.clientY + "px";

  document.body.appendChild(yourImage);
}
.mystyle {
  border-radius: 20px;
  box-shadow: 0px 0px 10px 0 rgba(0, 0, 0, 0.3);
  width: 60px; margin-left: -30px;
  height: 60px; margin-top: -30px;
  position: fixed;
}

Answer №2

Check out this elegant solution:

const images = [
  "/img/gallery/sunset.jpg", "/img/gallery/forest.jpg",
  "/img/gallery/beach.jpg", "/img/gallery/mountain.jpg",
  "/img/gallery/city.jpg", "/img/gallery/desert.jpg",
  "/img/gallery/waterfall.jpg", "/img/gallery/skyline.jpg",
  "/img/gallery/lake.jpg"
]; 

function displayImage(event) {
  var randomIndex = Math.floor(Math.random() * images.length); 
  var imgElement = document.createElement("img");
  
  imgElement.src = images[randomIndex];
  imgElement.style.cssText = `top: ${event.clientY}px; left: ${event.clientX}px;`;
  
  document.querySelector('body').append(imgElement);
}

document.addEventListener('click', displayImage);
img {
  border-radius: 20px;
  box-shadow: 0px 0px 10px 0 rgba(0, 0, 0, 0.3);
  z-index: -2;
  width: 360px;
  height: auto;
  position: fixed;
}

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

Timing problem in AngularJS service when sharing data with components on a single page

I am encountering an issue while using multiple components on a composite page and trying to reference data from a common service. The main problem arises when I attempt to create the object in the service within the first component and then access it in t ...

I am having trouble understanding why my GraphQL query is not retrieving any data from the WordPress GraphQL API when using SWR

I have created a query to retrieve my WordPress navigation menus using the WordPress graphql plugin along with swr, graphql, graphql-request, and next.js on my local files. When I add the query on the wp-grphql section of my site, I am able to successfully ...

"Transforming Selections in Illustrator through Scripting: A Step-by-Step Guide

In Illustrator, I successfully used an ExtendScript Toolkit JavaScript code to select multiple elements like text, paths, and symbols across different layers. Now, I am looking to resize them uniformly and then reposition them together. While I can apply ...

Display only the static placeholder in Angular 2 multi-select feature

My experience with angular 4 is fairly new and I've recently delved into using the angular multiselect feature with the npm package available here. I've managed to successfully configure it, as well as capture selected and deselected items/event ...

Guide to sending an HTML document containing images using the express framework

Is there a way to send an HTML file along with images using express? I have the following code that handles sending the initial page (index.html) to users. However, this page contains elements such as images and css files which are not being transferred p ...

Accumulation of style from various directives in AngularJS on a single element

Currently, I am working on developing a component framework and find myself in need of a method to apply styles from multiple directives to an element in a way that they can accumulate. The priority of the styles should be determined by the directive creat ...

Ways to display the data within a BLOB object

On this page, the user is showcasing a table with three columns - tipo_esame (string), data_esame (string), and uri (BLOB). const archiveItems = this.state.archive.map((archive, i) => { return ( <tr key={archive.hash_referral}> <td ...

Two selection options controlling filters. The first choice influences the data shown in the second filter

I've been struggling for hours to figure out how to build this functionality. My code seems to be getting close, but I'm having trouble passing my selection from the HTML back to the controller. Here's my Angular code: var Categories = Pa ...

Manipulating database records with Laravel 5.0: deleting and modifying data

Is there a way to manage database entries in Laravel 5.0 using the public functions destroy and edit? I am working on my library and need to make changes to the database entries @foreach ($allJobs as $job) <tr> <td><img src="{{ ...

Tips for invoking a JavaScript class method from an HTML document

I've created a Typescript class that dynamically inserts an HTML element to a page after it's loaded. Here is the code snippet: const calcElement: string = ` <div class="container"> <span class="cc-title">Field</span> ...

onload function prevents further URL redirection

After submitting the form "View this product," a function is triggered to retrieve the product id from the form data. Although I can successfully obtain the form_data, the page does not redirect as expected. I suspect that my function may not have been pr ...

How come my data is not appearing on the screen despite receiving a result in the console log?

I am facing an issue with displaying data obtained from Supabase. I am passing the data as a prop and using map to iterate over it in order to show the required values. However, despite logging the correct results for `programme.title`, nothing is being re ...

What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this: $scope.users = [ { ID: "1", Name: "Hege", Username: "Pege", Password: "hp", }, { ID: "2", Name: "Peter", User ...

When you log a JavaScript array after making a call using $.ajax, it may return an index

I am experiencing an issue with my array of 10 elements. When I log their key, value pairs in a loop, they are correctly ordered. $.each( sArray, function(i, k) { log(i, k); // log(i, k) returns correctly // [0] ELEMENT ONE // [1] ELEMENT TW ...

What steps can I take to resolve this issue when encountering an error during npm install?

As a newcomer to programming, I am embarking on the creation of a Discord bot using node and discord.js. My current hurdle involves the installation of a library named canvas, which seems to be causing issues. After developing and testing my application o ...

Clicking on the overlaying divs in the slideshow does not trigger any changes when clicked

My question is about the behavior of the href attribute in a fade-style animation. Even when different containers are visible, the href value remains constant. Below is the HTML code: <div id="teaserslider"> <ul> <li> ...

Enhance Your List with Icon Decorations

Is it feasible to utilize a sprite image in place of the default bullet for an ul list? Is this achievable? ...

Is it possible to refresh AdSense banner when the router changes?

Is there a way to reload the AdSense banner ads when the router changes? I've been encountering issues trying to re-add the script and HTML properly. Any guidance on how this should be done would be greatly appreciated... This is just a test for one ...

Can you choose and generate identical values using react-select?

I am working on implementing a multi Creatable feature where users can select a preset value or create a new value during the same interaction. To illustrate, here is my current render: import CreatableSelect from 'react-select/creatable'; functi ...

What's the best way to position an ion-label at the top of the stack

I'm having trouble creating an input label similar to the new Google style. However, when the label moves up, it gets cut in the middle as shown here. Despite trying to adjust the margin, padding, and Z-index, none of these solutions have resolved my ...