-2

So im new to jquery and I want to make a new navigation menu. I want this jquery script to color my list items randomly in a variety of colors of my choosing. Lets just say red, yellow, green, blue and black. Also it should not be possible to have the same color before and after a color is selected.

Further more I want this menu to have a hover function, so that once you hover one of the list items, all the other list items get the color of grey or another css value.

I hope someone could help me build this.

I know I haven't done much yet.

HTML:

<div id="wrapper">
    <div id="nav">
        <ul id="navigation">
            <li>Home</li>
            <li>About</li>
            <li>Products</li>
            <li>Blog</li>
            <li>Contact</li>
        </ul>
    </div>
</div>

Jquery:

$(document).ready(function() {
    $('#navigation, li').addClass('blue');
});

CSS:

* {
    margin:0px; padding:0px;
}
body {
    background-color:#999;
}

#wrapper {
    width:960px; margin:auto; background-color:#CCC;
}
.blue {
    color:#567;
}

Demo on jsfiddle, link: http://jsfiddle.net/iBertel/vbpXP/11/

user1562679
  • 145
  • 1
  • 3
  • 10

5 Answers5

3

Using @massivePenguin's idea Here you go, basically, we create an array, a few css rules with a default hover state of grey on all elements in the list. We end up with this result which has a randomised colour effect.

This is the key that randomises your array. The magic happens here, to make this a better effect, add 5 or so more colours to the array to add to the "random" effect.

colours.sort(function() {return 0.5 - Math.random()});

The above code is the key factor in the below script.

var colours = ['red', 'yellow', 'blue', 'green', 'pink'];
$(document).ready(function() {
    $('#navigation li').hover(function() {
        colours.sort(function() {return 0.5 - Math.random()});
        $(this).addClass(colours[0]);
    }, function() {           
        $(this).removeClass(colours[0]);      
    });
});​

http://jsfiddle.net/shannonhochkins/QkWXN/

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95
  • Yes almost, i just need the colors on the list items active so that 1 is red, another is yellow, third is blue etc. and then only when you hover an list item all other list items should lose their color and get a new color (like grey) – user1562679 Oct 01 '12 at 12:09
  • I have edited my answer for you. – Shannon Hochkins Oct 01 '12 at 12:36
  • @user1562679 This does all you have asked for, randomises the colours so that each time you hover over the same link it's different, all others become grey once hovered. Hope this helps. – Shannon Hochkins Oct 01 '12 at 12:45
  • This is perfect! Thanks a lot. Just one last thing... all the list items needs to be colored when not hovered and when hovered only the hovered should have color and the rest should grey out... Is this fixable? – user1562679 Oct 01 '12 at 12:48
  • Glad to have helped, +1 to @massivePenguin because he gave me the idea. Sometimes the simplest of things can make the best difference. – Shannon Hochkins Oct 01 '12 at 12:49
  • Just one last thing... all the list items needs to be colored when not hovered and when hovered only the hovered should have color and the rest should grey out... Is this fixable? – user1562679 Oct 01 '12 at 12:50
  • I have edited my fiddle for you. @user1562679 – Shannon Hochkins Oct 01 '12 at 12:56
  • Thats just perfect! Thanks again - love how simple its made. Cheers – user1562679 Oct 01 '12 at 13:01
2
  1. Put your classes into an array (e.g. var colours = ['red','yellow','green','blue','black'])
  2. Shuffle the array (see How to randomize (shuffle) a JavaScript array?)
  3. Instantiate a counter variable (e.g. n)
  4. Use an .each() function to:
    • Apply the value of the colour array's counter index (eg colours[n]) to the list item on hover
    • Increment the counter variable (e.g. n++)

e.g.

$('#nav li').each(function(){
    var switchColour = colours[n];
    $(this).hover(function(){
        $(this).addClass(switchColour);
    },
    function(){
        $(this).removeClass(switchColour);
    })
    n++;
});
Community
  • 1
  • 1
MassivePenguin
  • 3,701
  • 4
  • 24
  • 46
  • This sounds interesting, can you jsfiddle a solution please? – user1562679 Oct 01 '12 at 12:14
  • JSFiddle here: http://jsfiddle.net/DsxHz/ – MassivePenguin Oct 01 '12 at 12:27
  • Ah i see your fiddle... nice! Is it possible to make the script add a random class of 5 different classes instead of that n1? So that i can use css to color em? I meen so i dont have to add a class my self from the beginning. – user1562679 Oct 01 '12 at 12:30
  • n is a counter variable - it's a numeric value that starts at 0 and is incremented by 1 for each list item in $(#nav), so its final value in this example would be 4. To use more colours, just add them to the array; providing you have at least as many colours in the array as you do list items, you shouldn't have a problem. – MassivePenguin Oct 01 '12 at 12:34
  • yes i understand, but this way i will need to add a class to my li for it to work right? EDIT: Actually this can work! Thank you very much, saved my day. – user1562679 Oct 01 '12 at 12:35
  • n is used to pick the nth element in the colours array: e.g. if colours is ['red','blue','green','yellow','black'] then colours[3] would be 'yellow' (arrays in Javascript are zero-indexed, meaning the first element is [0] and not [1]; that's why we start n off at 0). – MassivePenguin Oct 01 '12 at 12:37
  • 1
    There's no need to use JavaScript for the hover event. Just use `:hover` on the CSS classes. – mekwall Oct 01 '12 at 12:37
  • true! You'd then only need to use .addClass for each li rather than the whole hover() function. – MassivePenguin Oct 01 '12 at 12:39
  • I have noticed that yours doesn't actually randomise the colours that are changing, I have posted a change to your code that fixes this with much less script too. – Shannon Hochkins Oct 01 '12 at 12:40
  • This is exactly how my answer is working... – mekwall Oct 01 '12 at 12:40
  • I don't mean to argue @MarcusEkwall, although if you view your fiddle, the colours are not randomising. You can also do this with a lot less code. Just trying to help. – Shannon Hochkins Oct 01 '12 at 12:42
  • You also don't need to use a counter in my version. It's very simple – Shannon Hochkins Oct 01 '12 at 12:44
  • Shannon can you post a fiddle of a working solution? I also still need to make it so that when i hover one of the list items all other items will turn grey - is this possible? – user1562679 Oct 01 '12 at 12:45
  • @Shannon Colors have been randomized all the time. Not sure you are looking at my answer, and I'm not arguing ;) just pointing out that my answer fixes everything he is asking for, with the minimum amount of code. – mekwall Oct 01 '12 at 12:53
  • @MarcusEkwall It doesn't randomise on hover, which is exactly what he was asking for. Although he didn't point this out in his original question. What he originally asked for can be achieved with css lol :) – Shannon Hochkins Oct 01 '12 at 12:59
0

So you can achieve this with the following code:

$('#navigation li').mouseover(function () {
    // this in this context is the currently hovered list DOM element.
    $(this).siblings().addClass('desired-class');
}).mouseout(function () {
    $(this).siblings().removeClass('desired-class');
});

Just a note:

You have the same ID on two different elements. You should change that.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • Yea i see, that was a mistake - its corrected :-) Your code doesnt tell me how i can get each list item to get different colors (does it? It needs to pick one a certain number of classes and apply it) and not the same color as the list item before? – user1562679 Oct 01 '12 at 11:59
  • You'd be better off using [`.hover()`](http://api.jquery.com/hover/) for this kind of behavior. – mekwall Oct 01 '12 at 12:03
  • But i dont see how this is applying a random color to my list items? – user1562679 Oct 01 '12 at 12:03
0

For random colors on load, but not on hover, use this:

$(function(){
    // The list items
    var $listItems = $("#navigation li");
    // Classes we want to use
    var classes = "red yellow green blue black".split(" ");
    // Create a copy of the classes
    var classesToUse = classes.slice(0);

    $listItems.each(function(){
        // Reuse the same classes if we've used all up
        if (classesToUse.length === 0) { classesToUse = classes.slice(0); }
        // Generate a random class, remove that from classesToUse
        // and then add it to the element
        $(this).addClass(
            classesToUse.splice(
                Math.floor(Math.random() * classesToUse.length), 
                1
            ).join("")
        );
    });
});​

If you want a random color on each hover, do this:

$(function(){
    // The list items
    var $listItems = $("#navigation li");
    // Classes we want to use
    var classes = "red yellow green blue black".split(" ");
    // Function to generate a random class
    function getRandomClass() {
        return classes[Math.floor(Math.random() * classes.length)]
    }
    // Bind to hover so that we can generate a new class
    $listItems.hover(function(e){
        var $elm = $(this); 
        if (e.type === "mouseenter") {
            // Generate new class, add it to dataset and class
            var randomClass = getRandomClass();
            $elm.data("class", randomClass).addClass(randomClass);
        } else {
            // Remove previous class, if any
            $elm.removeClass($elm.data("class"));
        }
    });
});

See test-case at jsFiddle

mekwall
  • 28,614
  • 6
  • 75
  • 77
  • Yes but if i add more list items here it stop coloring them? – user1562679 Oct 01 '12 at 12:27
  • No it doesn't. But with this implementation you need one color per list item. Thought it would be better not to have any duplicate colors. – mekwall Oct 01 '12 at 12:39
  • It doesn't randomise mate, It's a little too extensive, you can do this very simply, have a look at my post @MarcusEkwall – Shannon Hochkins Oct 01 '12 at 12:51
  • @Shannon What are you talking about? The splice will pick a random item from `classesToUse` and then use that. When all classes have been used up, it will start randomizing from the the classes all over again. – mekwall Oct 01 '12 at 12:55
  • 1
    Ah. It's not randomizing on hover, that's right. His question was too diffuse to make that out. – mekwall Oct 01 '12 at 12:56
  • He asked for random colours to be assigned every time the user hovers, if you hover over one of your links over and over it's still the same colour. @MarcusEkwall – Shannon Hochkins Oct 01 '12 at 12:57
  • @MarcusEkwall I know, it wasn't the best description of what he was after at all – Shannon Hochkins Oct 01 '12 at 12:58
  • @Shannon Updated my example. Not that fond of using `.sort` to shuffle the array. – mekwall Oct 01 '12 at 13:11
  • Why? The function is specifically built for arrays @MarcusEkwall – Shannon Hochkins Oct 01 '12 at 14:55
  • @Shannon Because you are traversing the whole array and shuffling indices around, instead of just accessing a random index. It's slower and will be harder to modify later on since you don't know what's where. – mekwall Oct 01 '12 at 15:03
0

Maybe, something like this? : demo jsFiddle

A color can't be next to the same color. But, it's a random selection, so there can be twice the same color, even if all the colors have not been picked yet.

Edited with hover

var myColors = ['blue', 'red', 'green', 'yellow'], previousRandom = '';

$(function() {
    var li = $('#navigation li');
    li.each(function(i){
        var t = $(this), random;
        do{
            random = Math.floor((Math.random() * myColors.length ));
        }while(random == previousRandom);
        t.addClass(myColors[random]);
        previousRandom = random;
    });

    li.hover(
        function(){ $(this).siblings().addClass('neutral'); },
        function(){ $(this).siblings().removeClass('neutral'); }
    );
});​
CronosS
  • 3,129
  • 3
  • 21
  • 28