V Neal
V Neal

Reputation: 419

Amending this jquery to assign a random border colour to each link on page

I've a series of links on a page that I'd like to have different border colours on the bottom. Obviously I can style this up using CSS targeting the parent div, however I figured there must be an easier way to do this with jquery if I've an array of colour values.

I found this function, which adds the border on hover, but I'd like to change it so it add's it to the p a as the default. Hope this makes sense.

Not really sure how to go about this... any pointers would be great...

<script>
$(document).ready(function() {
    $("p a").hover(function(e) {
        var randomClass = getRandomClass();
        $(e.target).attr("class", randomClass);
    });
});

function getRandomClass() {
    //Store available css classes
    var classes = new Array("yellow", "pink", "green", "blue");

    //Give a random number from 0 to 5
    var randomNumber = Math.floor(Math.random() * 5);

    return classes[randomNumber];
}
</script>

Updated function

   $(document).ready(function() {
 $("p a").hover(function(e)
    {
        var randomClass = getRandomClass();
        $(e.target).attr("class", randomClass);
    });
});
function getRandomClass()
{
    //Store available css classes
    var classes = new Array("yellow", "pink", "green", "blue");

    //Give a random number from 0 to 5
    var randomNumber = Math.floor(Math.random()*4);

    return classes[randomNumber];
}
$(document).ready(function() {
    $("p a").each(function() {
        $(this).addClass(getRandomClass());
    });
});

Upvotes: 0

Views: 129

Answers (2)

user1726343
user1726343

Reputation:

This should do it:

$(document).ready(function() {
    $("p a").each(function(){
        $(this).addClass(getRandomClass());
    });
    $("p a").hover(function(e) {
        var randomClass = getRandomClass();
        $(this).addClass(randomClass);
    },function(e){
        $(this).removeClass();
    });
});

The problem was that the classes weren't getting removed, so the one that occurred in the css last would be the only one applied.

Upvotes: 0

Manse
Manse

Reputation: 38147

Something like this would do it :

$(document).ready(function() {
    $("p a").each(function() {
        $(this).addClass(getRandomClass());
    });
});

uses .each() to iterate over all a elements within p elements and adds a random class using .addClass()

Upvotes: 1

Related Questions