Вопрос

What I want to do:

I want to create a fake "YouTube bar" where my visitors can see how their ingroup has (allegedly) rated something. This "YouTube bar" should have a range between 1 = very negative to 10 = very positive.

What I've got so far:

It was no problem to create a "YouTube bar" where the range is between 0 = very negative and 10 = very positive (whereas 5 = neutral/middle point). In this case, I have got eleven numbers (from 0 to 10). But I am struggeling with converting the range to 1-10 (whereas 5.5 should be the middle point and I only got 10 numbers).

I know it should work with basic mathematics (maybe divide the random number by 100/11 und multiply it by 100/10?) but I'm feeling a little bit stupid for not figuring it out. This is my code so far (http://jsfiddle.net/AauvC/):

HTML

<div id="youtubeFake">
<table>
    <tr>
        <td> My Group Rating:</td>
        <td id="ownNumber"></td>
    </tr>
    <tr>
        <td colspan="2" class="youtubeBar"> 
            <div id="ownLeft"></div>
            <div id="ownRight"></div>
        </td>
    </tr>
</table>
</div>

CSS

#youtubeFake{
    width: 60%;
}

.youtubeBar {
    width: 60%;
    padding-bottom: 10px;
}

#ownLeft{
    background-color: green;
    height: 4px;
    float: left;
}

#ownRight{
    background-color: red;
    height: 4px;
    float: right;
}

#ownNumber,{
    text-align: right;
}

JQuery/Javascript

$(document).ready(function(){
    var ownPercentage = (Math.random()*90)+10;       //create random number between 10 - 100
    $('#ownLeft').width(ownPercentage + '%');        //left part of the bar (the green part)
    $('#ownRight').width(100-ownPercentage + '%');   //right part of the bar (the red part)
    document.getElementById('ownNumber').innerHTML = (ownPercentage/10).toFixed(1);   //write random number into the HTML document and divide it by 10 (so I have a number between 1-10 instead of 10-100)
});

I would be glad if you guys could give me a hint!

Thanks a lot!

Это было полезно?

Решение

You can normalize the number by getting the percentage of ownPercentage out of 90 (your total number (100) minus your start number (10)) and then multiplying by your total number (100):

var ownPercentage = (Math.random()*90)+10;
var ownPercentageWidth = ((ownPercentage - 10) / 90) * 100;
$('#ownLeft').width(ownPercentageWidth + '%');
$('#ownRight').width(100-ownPercentageWidth + '%');

10 would give 0% width, 55 would give 50% width and 100 would give 100% width.

JSFiddle.

if ownPercentage was 10, this would give:

> ((10 - 10) / 90) * 100
> (0 / 90) * 100
> 0 * 100
> 0

..and if it was 55:

> ((55 - 10) / 90) * 100
> (45 / 90) * 100
> 0.5 * 100
> 50

..and if it was 100:

> ((100 - 10) / 90) * 100
> (90 / 90) * 100
> 1 * 100
> 100
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top