Random values with Jquery do not work

Asked

Viewed 27 times

-1

I have this code with JQuery, He does this: With the loop as long as it is < 5 he adds 5 li’s in my html, and then it generates a size random and adds in CSS, but it doesn’t work, all of mine li’s are of the same value. No console.log(size), the values are generated correctly, but when I put in css he is fixed.

$(function () {
    for (let i = 0; i < 5; i++) {
        const bg = $('.bg-animation');

        bg.append('<li></li>')

        const li = $('.bg-animation li')

        const random = function (min, max) {
            return Math.random() * (max - min) + min;
        };

        const size = Math.floor(random(200, 400));

        li.css({
            'width': size + 'px',
            'height': size + 'px',
            'bottom': '-' + size + 'px',
        })
    }
})

1 answer

2


According to the jQuery documentation, the method css changes the style of ALL elements that match the selector.

Get the value of a computed style Property for the first element in the set of Matched Elements or set one or more CSS properties for Every Matched element.

Like $('.bg-animation li') selects all the li in .bg-animation, with each iteration ALL li are changed and have the same styles.

To solve this problem you can add the :last to your selector, to catch only the last li: $('.bg-animation li:last').

$(function () {
for (let i = 0; i < 5; i++) {
    const bg = $('.bg-animation');

    bg.append('<li>adicionado ' + i + '</li>')

    const li = $('.bg-animation li:last')

    const random = function (min, max) {
        return Math.random() * (max - min) + min;
    };

    const size = Math.floor(random(1, 50));

    li.css({
        'width': size + 'px',
        'height': size + 'px',
        'bottom': '-' + size + 'px',
    })
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="bg-animation">
  <li>início</li>
</ul>

  • Show, gosh, I didn’t know it, even with the documentation I didn’t preserve attention, I just went out copying aoskoaks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.