Insert a variety of images onto the page at the exact position where the user has

Looking to create a script that selects a random image from an array and displays it at the current mouse position. Additionally, you can click elsewhere to add a new image, allowing you to cover the entire page with random cat images if desired.

document.onclick = userClicked;
    function userClicked() {
    var x = event.clientX;
    var y = event.clientY;
    var cat = document.getElementById("cat1");
    cat.style.display = '';
    cat.style.position = 'absolute';
    cat.style.left = x - cat.width / 2 + 'px';
    cat.style.top = y - cat.height / 2 + 'px';

}
.image{
  width:100px;
  height:auto;
}
#cat1{
  background-color:red;
  width:100px;
  height:auto;
}
<div class="container">
        <img alt="catAppear" class ="image" id="cat1" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png"/>
  <img alt="catAppear" class ="image" id="cat2" style="display:none" src="https://static.toiimg.com/thumb/msid-67586673,width-800,height-600,resizemode-75,imgsize-3918697,pt-32,y_pad-40/67586673.jpg"/>
    </div>
</div>

Answer №1

To dynamically display images on a webpage, you can maintain an array of image sources, randomly select one from the array, and then add a new <img> element with the chosen source to the document.

const srcs = ['https://i.pinimg.com/originals/7a/af/0f/7aaf0f1d48f57b7779c0fbcf103c2d0f.jpg', 'https://www.coopmcs.com/dotclear/public/chat.png'];
document.onclick = userClicked;
function userClicked() {
    var x = event.clientX;
    var y = event.clientY;
    const img = document.createElement('img');
    img.classList.add('image');
    img.src = srcs[Math.floor(Math.random() * srcs.length)];
    img.width = '150';
    img.height = '150';
    img.onload = function(){
      img.style.left = x - img.width / 2 + 'px';
      img.style.top = y - img.height / 2 + 'px';
    }
    document.body.appendChild(img);
}
.image {
  position: absolute;
}

Answer №2

var img_cats = ['https://www.coopmcs.com/dotclear/public/chat.png',
'https://static.toiimg.com/thumb/msid-67586673,width-800,height-600,resizemode-75,imgsize-3918697,pt-32,y_pad-40/67586673.jpg'
        ]

document.onclick = userClicked;

    function userClicked() {
    var x = event.clientX;
    var y = event.clientY;
    var cat = document.getElementById("cats");
    cat.src = img_cats[Math.floor(Math.random() * img_cats.length)];
    cat.style.display = '';
    cat.style.position = 'absolute';
    cat.style.left = x - cat.width / 2 + 'px';
    cat.style.top = y - cat.height / 2 + 'px';

}
.image{
  width:100px;
  height:auto;
}
#cat1{
  background-color:red;
  width:100px;
  height: auto;
}
<div class="container">
        <img alt="catAppear" class="image" id="cats" src="" style="display: none"/>
    </div>
</div>

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

Looking for assistance with text alignment?

23 Years Young From: The Boogie Down Bronx Heritage: Puerto Rican Pride Trade: Master Tailor For a demonstration, click on this link ...

Shifting Elements - Navigation triggers subtle movements in CSS styles as you move across pages

I've noticed a strange issue on my website where certain elements seem to be shifting slightly when navigating between different pages. Here's a quick video clip demonstrating the problem. It appears that these elements are not staying static as ...

Can Rollup be utilized solely for processing CSS files?

I am curious about whether Rollup can be used solely for processing CSS files, such as css, scss, less, etc. For example, if I have a file called index.css in my src folder (the entry folder) and want Rollup to process it in the dist folder (the output fol ...

Centered Bootstrap 4 modal with responsive width

Struggling to create a BootStrap 4 Modal that is centered in the screen and adjusts its width based on content? You're not alone. Despite trying different approaches like the container fluid and CSS methods, achieving a variable width modal is proving ...

JavaScript error in the Electron browser is causing a glitch

I am a beginner in the world of Node.js, JavaScript, and Electron. My goal is to create a basic application that can open a local HTML file in a browser window. The local file contains some complex embedded JavaScript (TiddlyWiki). Below is a snippet of sa ...

Removing a key from an index signature in Typescript - a step-by-step guide

In my web application built with Angular, we encountered a need for a data type to store translations of strings in different languages. To address this requirement, a team member defined the following type: export class TranslatedString { [language: str ...

Can I use npm's jQuery in an old-school HTML format?

I am looking to incorporate jQuery into a project without having to rely on the website or CDN for downloading the library. As someone new to npm, I am curious to know if following these steps would be advisable or potentially problematic down the line. Wh ...

Communication between Laravel and controller using AJAX for exchanging information

I have a specific AJAX function being called from a view: function gatherProductData() { var productIds = []; $('#compare-widget tbody tr').each(function(i, ele) { productIds[i] = $(ele).data('product-id'); }); ...

Searching on Google for the Twitter Bootstrap documentation using the Google search

Seeking advice on creating a basic index page with a Google-style centered search bar using Twitter Bootstrap. Struggling to achieve desired aesthetics. Need help adding a search icon button to the right side of the search field. Utilized typeahead for fu ...

Firefox with Ajax bug bar

I have encountered an issue with my Navbar specifically on Firefox. The problem I am facing is that the Navbar is flickering, constantly growing and shrinking. Interestingly, this issue does not appear when using Chrome or Opera. I'm curious to know ...

Show items in the sequence of clicking

Is there a way to display elements in the order they're clicked, rather than their order in the HTML using jQuery? For example: CSS code: .sq{ display:none; } HTML Code: <a href="#" id="1">A</a> <a href="#" id="2">B</a> ...

Storing user input in an array with the use of JavaScript

Hey everyone, I'm new to JavaScript and have been struggling with a task that seems simple. I'm trying to store user input in an array and then display it in a specific div (eventually I want to create a table using the DOM and store the input th ...

experimenting with adding fresh choices to dropdown menu using ajax and jquery

When attempting to load a list of locations through ajax/jQuery, I encounter an issue. After typing a letter into the input field, the first response is displayed but subsequent responses are simply appended to it. I have tried using .html('') an ...

Retrieving HTML content from an AJAX request

Is it possible to query HTML data returned from an AJAX request? I attempted the following code: $.post("gethtml.php", { url: $url.val() }, function(data) { var $html = $(data), $links = $("link, script, style", $html), $body ...

I just stumbled upon Jupyter and I'm curious - can I utilize Javascript and store it in the cloud?

Yesterday evening, I stumbled upon Jupyter and began using it alongside Python. It seems like an excellent tool for coding, something that I've been in need of, but I'm not sure if I can integrate JavaScript with it. I noticed there are npm packa ...

Switch between various div elements

Looking for a way to toggle between different divs? Here's the scenario: You have a sidebar with a set of buttons. Upon entering the page, you only want the div containing the button group to be visible. However, when a specific button (e.g. Info) is ...

Animating meshes in Three.js with texture mapping

After conducting some research, I successfully exported an obj file to a .js file that can be imported by the JSON model of Three.js. However, I am now faced with the challenge of animating this model. Specifically, I have a bird model in .js format that I ...

Obtaining the login status of users on my website and displaying the number of users along with their names from the database using PHP

Can anyone assist me with figuring out how to retrieve the login status of users on my website and display the count of users along with their names from the database using PHP or jQuery? Alternatively, I am also interested in simply finding out the num ...

Ways to completely eliminate a global component in VueJS

I have a unique component named button-widget that has been globally registered. Vue.component('button-widget', { template: `<button>My Button</button>` }) Now, I am wondering how I can permanently delete this component. I do ...

Get rid of the dashed outline surrounding the selected button

One of my divs has a button inside that, when clicked, creates an outline around it. Here is what it looks like: https://i.sstatic.net/pEr53.png **Code: ** .slide-arrow { color: #fff; background-color: #9E9997; border: none; padding: 16px 10px ...