Page 1 of 1

Jquery --> Hoping To Add If Statement To While Loop

Posted: Fri Oct 16, 2009 2:01 pm
by jbh
Hey,

I am a jquery noob but I am slowly getting it. The thing is, I have this free piece of code I am reverse engineering
that is the guts of a multi-star rating system. The part that determines which CSS class to use (hover) depending on the rating (I go from -5 to 5)
is all located in this while statement:

Code: Select all

    while(hovered > -6) {
                $("#rating_"+rid).children(".star_"+hovered).children('img').addClass("hover");
                hovered--;
            }
           
What this is doing is saying "If the value is greater than -6, and a mouse goes over it, take the 'hover' css class for the
specific star. Ok, no problem. My goal is to get that piece of code to say, within the loop

If hover == 5, use .addClass("hover5")

If hover == 4 use .addClass("hover4")

...

if hover ==-5 use .addClass("hovern5)

The idea is that while the loop is working, I want to use 10 conditionals and use 10 unique CSS classes
instead of being forced to use .hover. For reference, the .hover class tells the star to go fro a blank star to a filled up one
But I want to use 10 stars with 10 different hover images. Hence, 10 css classes are idea for me (hover 1 - 10 or something like that)

Is THAT possible? To have the if hover == conditional, for each value, in that loop?

Thanks

Re: Jquery --> Hoping To Add If Statement To While Loop

Posted: Tue Oct 20, 2009 11:25 am
by jbh
If I may ask, does javascript frown on my kind of logic? Should I be looking to use another method to achieve
the same end result? I am willing to research anything, it's just that I am more of a web programmer than a client side.

Re: Jquery --> Hoping To Add If Statement To While Loop

Posted: Tue Oct 20, 2009 4:15 pm
by McInfo
Try this example.

jQuery JavaScript:

Code: Select all

// jQuery is ready.
$(document).ready(function(){
    // Finds elements with an id beginning with "rating_", the children of those
    // elements with a class beginning with "star_", the children of those
    // children who are divs, then applies a hover effect to those divs.
    $('[id^=rating_]').children('[class^=star_]').children('div').hover(function(){
        // Using the current div, finds the parent of the current div, gets the
        // parent's class attribute, splits the class on the "_" into an array,
        // takes the value of the second element of the array, then assigns the
        // value to a variable n.
        var n = $(this).parent().attr('class').split('_')[1];
        // Using the current div, adds a class to the div. The class name begins
        // with "hover_" and ends with a string from the variable n.
        $(this).addClass('hover_' + n);
    }, function(){
        // Assigns a variable n as before.
        var n = $(this).parent().attr('class').split('_')[1];
        // Removes the class that was added before.
        $(this).removeClass('hover_' + n);
    });
});
HTML body content:

Code: Select all

<ul id="rating_1">
    <li class="star_5"><div>5</div></li>
    <li class="star_4"><div>4</div></li>
    <li class="star_3"><div>3</div></li>
    <li class="star_2"><div>2</div></li>
    <li class="star_1"><div>1</div></li>
    <li class="star_0"><div>0</div></li>
    <li class="star_n1"><div>n1</div></li>
    <li class="star_n2"><div>n2</div></li>
    <li class="star_n3"><div>n3</div></li>
    <li class="star_n4"><div>n4</div></li>
    <li class="star_n5"><div>n5</div></li>
</ul>
CSS:

Code: Select all

li div {
    border: solid 1px #000;
    background-color: #080;
    width: 40px;
    height: 40px;
    margin-bottom: 4px;
}
.hover_5  { background-color: #FF005F; }
.hover_4  { background-color: #EF006F; }
.hover_3  { background-color: #DF007F; }
.hover_2  { background-color: #CF008F; }
.hover_1  { background-color: #BF009F; }
.hover_0  { background-color: #AF00AF; }
.hover_n1 { background-color: #9F00BF; }
.hover_n2 { background-color: #8F00CF; }
.hover_n3 { background-color: #7F00DF; }
.hover_n4 { background-color: #6F00EF; }
.hover_n5 { background-color: #5F00FF; }
Edit: This post was recovered from search engine cache.

Re: Jquery --> Hoping To Add If Statement To While Loop

Posted: Tue Oct 20, 2009 10:10 pm
by McInfo
I just recently decided to learn jQuery, so I'm a beginner too. I gave this another try to get some practice and think I've found a pretty good solution.

I'm assuming you are working with the tutorial found on webtint.net. (The code matches.) The following example uses the same HTML structure as the tutorial and the same CSS along with some additional CSS shown below. This jQuery code is a replacement for the hover effect described in the tutorial.

jQuery:

Code: Select all

// To do when jQuery is ready
$(document).ready(function(){
    // Gets those rating star images
    var those = $('[id^=rating_]').children('[class^=star_]').children('img');
    // Defines a hover effect
    those.hover(function(){
        // The sibling index of the current image. The index of the first
        // sibling is 0.
        var i = those.index(this);
        // Removes the "hover" class and all of the "hover_" classes from the
        // current image. There should be as many "hover_" classes defined in
        // CSS as there are images. Each should be numbered starting with 0. The
        // number those.size() represents the number of images. The range()
        // function is a custom function that is defined elsewhere. It returns
        // an array of numbers. The join() method is applied to the array to
        // create a string like "0 hover_1 hover_2".
        those.removeClass('hover hover_' + range(0, those.size()).join(' hover_'));
        // Adds a "hover" class and a "hover_" class to the current image and
        // previous siblings. The slice() method returns a portion of the array
        // it is applied to.
        those.slice(0, (i + 1)).addClass('hover hover_' + i);
    });
});
JavaScript range() function: Acts like PHP's range() function (but does not support character ranges).

Code: Select all

function range (low, high /*[,step]*/) {
    var range = new Array();
    var step = (arguments.length == 3) ? Math.abs(arguments[2]) : 1;
    if (low < high) {
        for (var n = low; n <= high; n += step) {
            range.push(n);
        }
    } else {
        for (var n = low; n >= high; n -= step) {
            range.push(n);
        }
    }
    return range;
}
Additional CSS: See the webtint.net tutorial for the rest of the CSS.

Code: Select all

img { border: solid 3px #FFFFFF; }
.hover_0  { border-color: #0F00FF; }
.hover_1  { border-color: #AF00AF; }
.hover_2  { border-color: #FF000F; }
/* Add a hover for each star. */
HTML: See the webtint.net tutorial for the images and the rest of the HTML.

Code: Select all

<div id="rating_1">
    <span class="star_0"><img src="star_blank.png" alt="" /></span>
    <span class="star_1"><img src="star_blank.png" alt="" /></span>
    <span class="star_2"><img src="star_blank.png" alt="" /></span>
    <!-- Add more stars if you want. -->
</div>
Edit: This post was recovered from search engine cache.

Re: Jquery --> Hoping To Add If Statement To While Loop

Posted: Tue Oct 20, 2009 11:38 pm
by McInfo
Okay...third try. This version behaves more like what you are looking for. Each CSS class is related to a sibling index, so each image has its own class.

Code: Select all

$(document).ready(function(){
    var those = $('[id^=rating_]').children('[class^=star_]').children('img');
    those.hover(function(){
        var i = those.index(this);
        // Removes all "hover" and "hover_" classes
        for (var n = 0; n <= those.size(); n++) {
            those.eq(n).removeClass('hover hover_' + n);
        }
        // Add "hover" and "hover_" classes to siblings up to and including the
        // current index
        for (var n = 0; n <= i; n++) {
            those.eq(n).addClass('hover hover_' + n);
        }
    });
});
The loops could be written different ways. Using a while...

Code: Select all

var n = 0;
while (n <= those.size()) {
    n++;
}
...or using a for-in and the range() function I posted earlier:

Code: Select all

for (var n in range(0, those.size())) {
}
Edit: I just realized that all three of my solutions are limited to one rating div per page because the sibling index is relative to all images that are a child of a rating div. :(

Edit: This post was recovered from search engine cache.

Re: Jquery --> Hoping To Add If Statement To While Loop

Posted: Wed Oct 21, 2009 1:45 pm
by jbh
First of all, thank you for doing all of this.

Second, do you think that this means that there is no real solution from the code listed? That it's not possible
to have 10 hover classes activated for 1 image per class?

Thanks

Re: Jquery --> Hoping To Add If Statement To While Loop

Posted: Wed Oct 21, 2009 2:49 pm
by McInfo
There is a solution. I just didn't find it because I went off in a different direction. Then I got tired and had to get some sleep. The effect you want is entirely possible, though.

By using each(), we can encapsulate the behavior so it affects only all images within a given rating instead of all images in all ratings.

Code: Select all

$(document).ready(function(){
    $('[id^=rating_]').each(function(){
        var those = $(this).children('[class^=star_]').children('img');
        those.hover(function(){
            var i = those.index(this);
            for (var n = 0; n <= those.size(); n++) {
                those.eq(n).removeClass('hover hover_' + n);
            }
            for (var n = 0; n <= i; n++) {
                those.eq(n).addClass('hover hover_' + n);
            }
        });
    });
});
Edit: This post was recovered from search engine cache.

Re: Jquery --> Hoping To Add If Statement To While Loop

Posted: Wed Oct 21, 2009 4:27 pm
by jbh
Interesting. I will test this out and update you. I really appreciate the input. It's just
hard to find real world examples *like this* via google with jquery
so this will be a tremendous asset in helping me grasp this.

Thanks again.

Re: Jquery --> Hoping To Add If Statement To While Loop

Posted: Wed Oct 21, 2009 5:23 pm
by McInfo
Understanding JavaScript is the key to understanding jQuery. The site javascript.crockford.com has some good information about JavaScript, especially the "survey" page which gives an overview. It's too bad that JavaScript doesn't have well-maintained, official manual like PHP does. There is some reference material, though.

Edit: This post was recovered from search engine cache.