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

Creating a Vertical Navbar Dropdown in Bootstrap 3.0 Without Appending to the Last List Item Only

Currently, I'm in the process of creating a panel layout that features an elegant vertical navbar. Although everything seems to be aligned correctly and I've managed to implement a dropdown menu in a vertical layout, it keeps appending to the las ...

Extract specific nested elements

Looking for assistance with extracting specific nested objects from a series structured like so: data = {"12345":{"value":{"1":"2","3":"4"}}, {"12346":{"value":{"5":"6","7":"8"}}, {"12347":{"value":{"9":"0","11":"22"}} In need of creating a functio ...

Tips for accessing the value and text of an Angular Material mat-select through the use of *ngFor

When using a dropdown menu, I want to retrieve both the value and text of the selected option. View dropdown image Underneath the dropdown menu, I aim to display values in the format of "options: 'value' - 'selected option'". compone ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

Obtain span value using a CSS selector in Python

I need help extracting the value of a span using a CSS selector soup = BeautifulSoup("<body><main><div class='rentalprice'><span>3.000</span></div></main></body>") pagecontent = soup.find( ...

The audio directory is not included in the build of the Ionic framework, causing it to be skipped and absent

Recently, I've been working on an Ionic/Cordova app and came across a folder labeled /audio which consists of mp3 files: /www /assets /audio file.mp3 /css /js config.xml index.html The issue at hand is that the /audio directory is n ...

The Socket IO server fails to broadcast a message to a designated custom room

I am currently working on developing a lobby system that allows players to invite each other using Socket io version 4. The process involves the client sending a request to create and join a room, followed by emitting messages to other clients in the same ...

Display a hoverable button for a singular element within an array during the process of mapping through the array

const ChatWidget = () => { const bodyRef = useRef(null) const [{messages,roomMessages,roomID,socket,user}, dispatch] = useStateValue() const [dropdown, setDropdown] = useState(false) useEffect(()=>{ const setScreen = () =>{ bodyRef.cur ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

Some characters are not compatible with the CSS writing-mode feature

There seems to be an issue with the CSS writing mode not applying correctly to the symbol '№'. Here is an example: <html> <head></head> <body> <p style="writing-mode: vertical-lr;"> Номер № ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

JavaScript Selenium code encountering an "Element not interactable" error with input textbox element

Currently, I am attempting to utilize Selenium in order to automate inputting a location into the search bar on weather.com. Initially, I wrote the code in Python and it seems to be functioning properly: // this works driver = webdriver.Chrome(ChromeDriver ...

Showing the SQL table data output

Attempting to present a new table based on the SQL query result. Below is the initial table code shown when the user first loads the page. TABLE: <form action="walkthroughs.php" method="POST"> Platform: <input type="text" name="platform" ...

Check Image Dimensions prior to Image Loading

I've been working with JQuery Masonry and would like to incorporate Lazy Load using a WordPress plugin to load images only when they come into view. The issue I'm facing is that when Lazy Load is used, the masonry elements don't recognize t ...

modify CSS style once the modal has been hidden

Is there a way to change the default background color of my table row back to normal after closing the modal window that appears when I click on it? <tr class='revisions'> <td>{{ $revision->date_of_revision->format(' ...

Transforming HTML Code in a PHP Document to a PDF Document

I have a PHP file that interacts with a database to update the HTML content. There is a button on the page labeled "Export As PDF". I attempted to convert the page to a PDF using HTML2FPDF, but encountered this error message: FPDF error: Unable to create ...

Tips for ensuring a webpage loads at a specific resolution

I recently created a website on my computer with a screen resolution of 1920x1020. However, when I view it on other machines with a 1366x768 resolution, the website appears distorted. Is there a way to set a fixed resolution for my website to ensure it l ...

Error: Angular7 Unable to locate namespace 'google'

I am currently utilizing the import { MapsAPILoader } from '@agm/core'; package to enable auto-complete address search functionality. However, I have encountered an error message stating cannot find namespace 'google'. The error occu ...

Getting data from a URL using Node.js and Express: A beginner's guide

Currently, I am facing an issue with extracting the token value from the URL http://localhost:3000/users/reset/e3b40d3e3550b35bc916a361d8487aefa30147c8. My get request successfully validates the token and redirects the user to a password reset screen. Howe ...

Can you please specify the type of values being entered as input?

Query: How do I identify the data type of the value entered in an input field? Whenever I use typeof, it always returns string unless the string is empty. I searched various forums extensively but couldn't find a solution. Can someone assist me with t ...