Placing icons in a div at arbitrary positions using VueJS

I am looking to create a unique div where I can position multiple material design icons randomly.

For example:

Link to Example Image

Previously, I achieved this using jQuery. Now, I want to achieve the same result using VueJS with material design icons instead of shapes.

for (var i = 0; i < 10; i++) {
  $('.main').append('<div class="box"></div>');
}
$( '.box' ).each(function( index ) {
  $(this).css({
    left : Math.random() * ($('.main').width() - $(this).width()),
    top : Math.random() * ($('.main').height() - $(this).height())
  });
});
.main {
  width: 600px;
  height: 400px;
  background: #f0f0f0;
  position: relative;
}

.box {
  width: 20px;
  height: 20px;
  background: black;
  border-radius: 50px;
  position: absolute;
  /* parent width - box width */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main"></div>

Answer №1

A unique approach utilizing a single file component within a Vue CLI project:

To replicate your traditional for-loop, we leverage Vue's list rendering. By assigning template refs to elements like .main and .box, we obtain references necessary for the calculations below:

<template>
  <div ref="main" class="main">
    <div ref="box" class="box" v-for="i in 10"></div>
  </div>
</template>

Using these element references, we utilize clientWidth and clientHeight to derive box dimensions upon mounting:

<script>
export default {
  async mounted() {
    // ensure $refs are ready
    await this.$nextTick()

    this.$refs.box.forEach(box => {
      box.style.left = Math.random() * (this.$refs.main.clientWidth - box.clientWidth) + 'px'
      box.style.top = Math.random() * (this.$refs.main.clientHeight - box.clientHeight) + 'px'
    })
  }
}
</script>

You may simply copy the original CSS into a <style> block:

<style>
.main {
  /* include original .main styles here */
}

.box {
  /* include original .box styles here */
}
</style>

demo 1

For a creative twist, follow similar steps using SVG paths to display random Material Design icons. For example, bind a <path> to a randomly selected SVG path from @mdi/js (based on MDI library):

  1. Set up a data property named "icons" and populate it with a range of random icons sourced from @mdi/js:

    import * as mdiIcons from '@mdi/js'
    
    function randomInt(min, max) {
      min = Math.ceil(min)
      max = Math.floor(max)
      return Math.floor(Math.random() * (max - min) + min)
    }
    
    function randomIcons(count) {
      const allIcons = Object.values(mdiIcons)
      const start = randomInt(0, allIcons.length - count)
      return allIcons.slice(start, start + count)
    }
    
    export default {
      data() {
        return {
          icons: randomIcons(10),
        }
      },
    }
    
  2. Substitute <div ref="box"> from the previous example with <svg ref="box">. Inside the <svg>, add

    <path :d="icons[i]" />
    to bind to the generated random icons.

    <template>
      <div ref="main" class="main">
        <svg ref="box" class="box" v-for="i in 10">
          <path :d="icons[i]">/>
        </svg>
      </div>
    </template>
    

demo 2

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

Is it possible to align a BootstrapVue b-form-checkbox&radio in a vertical center within Vuetify

I'm currently utilizing Vuetify as our primary framework and incorporating some Bootstrap-Vue components such as b-form-checkbox and radio. I am facing a challenge in trying to vertically center my Bootstrap-Vue checkbox and text. I have attempted se ...

Determining the function responsible for triggering an ajax error

I've implemented a global error handler for handling ajax calls, where I capture the error details, send them to a PHP script, and then log the outcomes: $(document).ajaxError(function(event, request, settings){ //get the error and log the resul ...

Getting Your Redux Form Ready for Submission

I recently transformed my Redux form into a wizard with multiple subcomponents following the structure outlined here: However, I'm encountering difficulties when trying to integrate the form with my actions to submit the form data. Unlike the example ...

JavaScript for Acrobat

I am currently creating a form in Adobe Acrobat and incorporating additional functionality using JavaScript. I have been searching for information on the control classes for the form, such as the member variables of a CheckBox, but haven't found any c ...

Utilizing a jQuery variable within an .html() method

Can a Jquery if statement be used to display different content inside a div based on a variable? For example, if the variable is set to "cats", the displayed content might say "I like cats", and if it changes to "dogs", it would read "I like dogs". Is this ...

Can jQuery be used in Chrome Extensions?

I am facing an issue with my extension. Do I need to declare permissions? The "code:" line is not working in the background file. Here is the code from the Background File: chrome.browserAction.onClicked.addListener(function(tab) { // No tabs or host p ...

Continuously simulate mousewheel events

I'm trying to make my mousewheel event trigger every time I scroll up, but it's only firing once. Can you assist me with this issue? Please review the code snippet below. $('#foo').bind('mousewheel', function(e){ if(e.o ...

Struggling with developing a straightforward application with Angular-Material

My goal is to develop an application that utilizes the Angular Material navigation bar, as showcased in this example. Being relatively new to AngularJS, I'm facing an issue where my app loads but only displays a blank page. Below is the code snippet ...

I am facing difficulties accessing an element within a controller in Angular

Struggling to access an element inside an AngularJS controller, I attempted the following: var imageInput = document.getElementById("myImage"); Unfortunately, this approach was unsuccessful as the element returned null. Curiously, when placing the statem ...

Unlocking the secrets of parsing JSON within a script tag using Laravel and AngularJS

I am facing some confusion as I attempt to use JSON with Angular and Laravel (v5.2.11) Here is my plan: 1. Send JSON to a blade file 2. Retrieve JSON within a script tag and assign it to a variable 3. Display each data In order to avoid duplicating ...

Section is obstructing the view of Other Section above

I am struggling to create a responsive design for these two sections, both of which display quite similarly in line. Here are the resolutions for desktop and tablet/mobile: https://i.sstatic.net/XWbSP.png https://i.sstatic.net/3KLyY.png I suspect the is ...

What methods can I use to emphasize three distinct dates?

I'm facing difficulty highlighting three specific dates: "10-11-2020", "22-11-2020", and "07-11-2020" using React.js and Datepicker. Unfortunately, my attempts have not been successful so far. Here is the code snippet I am working with: import React, ...

Different ways to alter response headers using express-http-proxy

Context In my current project, I am utilizing the express-http-proxy package to facilitate requests between a Single Page Application (SPA) and a CouchDB instance. I have opted for handling this proxy setup on a per call basis rather than creating a dedic ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

Understanding how to display a component within another component in Vue.js

I am faced with a scenario where I have a component that has the following template: <div v-for:"item in store" v-bind:key="item.type"> <a>{{item.type}}</a> </div> Additionally, I have another component named 'StoreCompone ...

Dynamic Rendering and Retrieving Component HTML in Angular

Generate the HTML code of a component to open a new tab with an about:blank page. Reason: This method helps avoid creating HTML using string variables, such as: var html = '<div> <h3>My Template</h3> &a ...

Adding External HTML Content to a JQuery Mobile Website

As I work on dynamically integrating an external HTML source into a jQuery mobile page, I encounter the issue of it not appearing as expected - lacking the jQuery mobile styling. Can anyone offer some guidance on what might be going wrong? Main HTML: < ...

Verify if input is selected using jQuery

Is it possible to achieve the following using jQuery? if($(this).parent().find('input:checked') == true) {$(this).find('.switch').attr('state','on');} else{$(this).find('.switch').attr('state',& ...

Using JQUERY to select all child checkboxes within a tree structure and check them all

I am looking to create functionality where checking the parent checkbox will automatically check all child checkboxes. While I have gotten this to work for the bottom parent checkbox, it does not seem to function correctly for any parent checkboxes highe ...

Overlap with upper picture formatting

I've been struggling to create an ion-card with two images: a main picture and a small book cover. Any ideas on how to achieve this? Note: The layout should have 2 images, one at the top and another as a small book cover. Check out this sample on St ...