Generate a unique border using jQuery randomization techniques

I've been experimenting with creating a random number and having the border-radius of my div change on every pageload:

<script>
$(".card-body").each(function(){
var rand = Math.floor(Math.random() * 100) + 1;
$(this).css( {  borderRadius:  rand } );
});
</script>

Is there a way to set the border radius similar to this css style?

border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;}

Answer №1

Check out the code snippet below:

Loop 8 times and increment (+=) the rand variable with a random number each time. After the 4th iteration, add a / to separate the numbers.

$(".card-body").each(function(){
var rand="";
for(var i=0;i<8;i++)
{
 rand += Math.floor(Math.random() * 255) + 1 + "px";
 if(i!=3)
  rand +=" ";
 else
   rand +="/ ";
 }
$(this).css( {  borderRadius:  rand } );
});
.card-body-static{
border:1px solid black;
border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
margin-bottom:15px;
}

.card-body{
border:1px solid black;
margin-bottom:15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card-body-static">static</div>

<div class="card-body">random</div>
<div class="card-body">random 2</div>

Answer №2

To tackle this issue, a solution involves forming an array of border-radius values and then combining them to create the CSS rule string.

  1. Start by creating a function that generates a random number between 1 and 100 :

    function generateRandomNumber(){
        return Math.floor(Math.random() * 100);
    }
    
  2. Retrieve the width of each card:

    $(".card-body").each(function(){
    
        const width = $(this).width();
    
       // ...
    
    });
    
  3. Next, form a new array containing two numbers ([ 0, 0 ]) :

    $(".card-body").each(function(){
    
        const width = $(this).width();
    
        const borderRadiusArray = [0,0];
    
        // ...
    
    });
    
  4. We need to iterate through this array multiple times to obtain an array of border-radius values. Initially, assign a random percentage to each element (using the generateRandomNumber function). Then, associate each percentage with a value by multiplying it by the object's width (a suitable reference point for our border-radius). Another iteration will add the 'px' string to each value. Finally, we merge these two elements together with a space in between.

    $(".card-body").each(function(){
    
        const width = $(this).width();
    
        const borderRadiusArray = [0,0];
          .map(value => generateRandomNumber())
          .map(percentage => width*percentage)
          .map(pixels => pixels + 'px')
          .join(' ');
    
        // ...
    
    });
    
  5. You can then apply this property to the object:

    $(".card-body").each(function(){
    
        const width = $(this).width();
    
        const borderRadiusArray = [0,0];
          .map(value => generateRandomNumber())
          .map(percentage => width*percentage)
          .map(pixels => pixels + 'px')
          .join(' ');
    
        $(this).css( {  borderRadius:  borderRadiusArray });
    
    });
    

Below is the complete code snippet:

function generateRandomNumber(){
return Math.floor(Math.random() * 100);
}


$(".card-body").each(function(){

  const width = $(this).width();

const borderRadiusArray = [0,0]
    .map(value => generateRandomNumber())
    .map(percentage => width*percentage)
.map(pixels => pixels + 'px')
    .join(' ');
    
$(this).css( {  borderRadius:  borderRadiusArray });
  
});
.card-body {
  width: 200px;
  height: 100px;
  background-color: purple;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="card-body"></div>
<div class="card-body"></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

Shutting down the jQuery pop-up

I am struggling with trying to display this code as a popup on my website. Here is the code I have: <div id="myDialog" title="myTitle"> <div class="table_cell"> <div class="message"></div> </div> <div class="tabl ...

The issue of Jquery .click event handler failing to work for class selector specifically in CHROME

Is there a way to achieve the same opacity effect on click as on mouseover? I've tried various selectors without success. Any help on this issue would be greatly appreciated. Thank you in advance! .container { position: absolute; background:url(&a ...

Automatically switch to dark mode at specified times: A simple guide

Here is the current method for toggling themes: let themeToggler = document.getElementById('theme-toggler'); themeToggler.onclick = () => { themeToggler.classList.toggle('fa-sun'); if (themeToggler.classList.contains('f ...

Unusual issue: PDF content disappears upon reopening modal

I am trying to incorporate a PDF display within a Bootstrap modal. Inside the .modal-body, I have inserted the following code: <object width="1000" height="500" data="path/to/pdf" type="application/pdf"> ...

The issue with the page width is occurring due to a bug related to the

When pages contain the AddThis code, they tend to become very wide due to the code itself, resulting in a horizontal scroll bar appearing. However, by removing the code or changing the page direction to LTR, the issue is resolved and the page width return ...

Asking for information regarding RESTful API

Could you please assist me in identifying the most suitable technologies for integrating a RESTful API into an HTML and CSS website? The primary objective is to enable the website owner to easily log in and add news entries about their business. Addition ...

unable to retrieve parent ID

I am having trouble retrieving the ID of the parent's parent of the event target. It keeps coming back as undefined, but I have verified through firebug that the ID does exist. Below is my HTML markup: <div class="grid-stack-item ui-draggable ui- ...

Tips for hiding the overflow scrollbar on Microsoft Chrome when there is no content to scroll

Looking for a solution to hide scroll bars in Microsoft Chrome, but only when there is no content to scroll? The current div and styles always show the horizontal and vertical scroll bars, even when the height exceeds the content. <div style="backgroun ...

Showcase JSON data within a designated div

As someone new to HTML, JavaScript and Vue, I'm unsure if my issue is specific to Vue or can be resolved with some JavaScript magic. I have a Node.js based service with a UI built in Vue.js. The page content is generated from a markdown editor which ...

AngularJS: Changing color property using toggle when a CSS class is modified

After starting to learn AngularJS, I have been able to find many helpful answers on this forum. However, there is one particular issue that has been causing me frustration. My goal is to dynamically change the color property of an element only when it has ...

What is the best way to use Ajax to modernize an existing model with a new model

Currently, I am able to add and remove a product from the cart using Ajax. When a product is removed, it is deleted from the cart and the cart is updated dynamically: $.post("/Cart/RemoveFromCart", { "id": $(this).data('id' }. However, I now ne ...

unresolved string constant issue with a django template command

I encountered an issue with the code snippet below, which is resulting in an unterminated string literal error: $(function() { $('#addDropdown').click(function() { var $d = $('{{ form |bootstrap }}').fadeIn(). ...

What is the best way to obtain real-time DOM updates using jQuery?

Upon loading my webpage, various scripts are adding a significant amount of HTML code. Now, I am attempting to modify this additional HTML. For instance, there is a div element <div id="detail"><span>some content</span></div> that ...

The PowerShell script has misplaced the HTML formatting

I am a beginner in scripting and I have two questions. I wrote a .ps1 script to identify devices with less than 10% free space: Get-Content "C:\temp\servers.txt" | Sort | ForEach { $computer = $_ $disks = @(Get-WmiObject Win32_LogicalDisk -Com ...

Error in Chrome: Uncaught TypeError with JQuery Ajax - Unable to access property 'data' when null

Trying to retrieve results from the YouTube API, my code is as shown below: function Vget(strt){ $.get("https://gdata.youtube.com/feeds/api/videos", { q: "soccer, 'start-index':strt, 'max-results':"5", v:"2",alt:"jsonc" }, functi ...

Can you explain the significance of allow_blank and style = {`base_template` : `textarea.html`} in Django when used as attributes of a CharField?

Currently, I am delving into the world of Django REST framework through a step-by-step Tutorial. The Tutorial introduces serializers that function much like Django's forms to facilitate the serialization and deserialization of snippet instances into ...

Avoiding Page Reloads with Ajax while Removing Entries from a Table in Laravel

I am encountering an issue where I can click the button, but it requires a refresh to execute the delete action. Is there something in my ajax code causing this problem and why is it refreshing? I want the button to instantly delete without the need for a ...

What is the best way to ensure HTML validation during a pull request?

Are there any tools available to validate all specified files in a pull request? I have previously used Travis CI for testing and am now searching for a similar plugin focused on validation rather than tests, such as W3C validation. ...

Flyer - Chart "dimmed" and unselectable when dimensions are specified as a proportion

I am currently working on displaying a map within a container. I have successfully been able to display the map by setting its size to a specified number of pixels. However, my goal is to have the height of the map adapt to the size of the container dynami ...

Is there a way in CSS to set a label's width equal to the width of its content?

I am facing an issue where I need the question mark div to be positioned right next to the top row of text in the label it is associated with. Can someone suggest some styles that can be applied to the label to adjust the width and spacing so that it match ...