Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery toggle opacity with click

I have two divs (A and B) and two buttons and I'm trying to achieve this effect: when I click on one button the opacity of div A increase, while opacity of div B decrease, and vice versa. But it seems to work only when decrease... Can't understanfd what's wrong.

<!-- html -->
<div id="pippo"></div>
<div id="pluto"></div>
<div id="opacity">opacity</div>
<div id="opacity2">opacity2</div>


function changeOpacity() {


$( "#opacity" ).click(function() {
    var pippo = $('#pippo').css('opacity');
    var pluto = $('#pluto').css('opacity');
    $( "#pippo").css( "opacity", pippo + 0.1 );
    $( "#pluto").css( "opacity", pluto - 0.1 );
});
$( "#opacity2" ).click(function() {
    var pi = $('#pippo').css('opacity');
    var pl = $('#pluto').css('opacity');
    $( "#pippo").css( "opacity", (pi - 0.1)  );
    $( "#pluto").css( "opacity", (pl + 0.1)  );
    return false;
});
}
changeOpacity();

JsFiddle here

like image 992
uomopalese Avatar asked Nov 19 '25 21:11

uomopalese


1 Answers

The problem here is that the .css() method does not return a number - it in fact gives you a string. So when you try to execute something like:

var pippo = $('#pippo').css('opacity');    
$( "#pippo").css( "opacity", pippo + 0.1 );

If pippo was say, 0.9, then pippo + 0.1 would give you "0.90.1". The numerical 0.1 would be converted to a string, and you would get the concatenation of the two strings (since that is what the + operator does).

However, the reason why subtraction works, such as:

var pluto = $('#pluto').css('opacity');
$( "#pluto").css( "opacity", pluto - 0.1 );

Is because there is no subtraction operator for strings, and so pluto is automatically casted to a number.

To remedy this, consider using parseFloat() on returned values from .css():

function changeOpacity() {
    $("#opacity").click(function () {
        var pippo = $('#pippo').css('opacity');
        var pluto = $('#pluto').css('opacity');
        $("#pippo").css("opacity", parseFloat(pippo) + 0.1);
        $("#pluto").css("opacity", parseFloat(pluto) - 0.1);

        console.log(pippo + 0.1);
    });
    $("#opacity2").click(function () {
        var pi = $('#pippo').css('opacity');
        var pl = $('#pluto').css('opacity');
        $("#pippo").css("opacity", parseFloat(pi) - 0.1);
        $("#pluto").css("opacity", parseFloat(pl) + 0.1);
        return false;
    });
}

Here's a JSFiddle to demonstrate.

Hope this helps! Let me know if you have any questions.

like image 88
Serlite Avatar answered Nov 21 '25 12:11

Serlite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!