javascript - How to make jQuery variable toggle buttons? -
i'm making app can customize opacity of different elements. app has simple "up" , "down" buttons, increasing , decreasing opacity. however, toggle functions not implementing in css. here's html:
<div id="container">make me lighter.</div> <br> <br> <button id="up">up</button> <br> <button id="down">down</button>
css:
* { margin: 0px; padding:0px } #container { padding: 10px; border: 10px solid; }
and jquery:
$(document).ready(function () { var x = 0.5; $("#up").click(function () { var x = x += 0.2; }); $("#down").click(function () { var x = x -= 0.2; }); $("#container").css({ 'opacity', x }); });
this fiddle: http://jsfiddle.net/j96bu778/1/
i've spent lot of time looking questions on stack overflow, , of answers confusing understand. jquery api didn't me either.
thanks help.
there number of things wrong code (but don't discouraged!):
var x = x += 0.2;
not kind of assignment you're trying do. incrementsx
0.2
, assigns new local variablex
value of evaluatedx
. since x accessible scope of callback functions, usex += .2
.{ 'opacity', x }
incss
function argument not valid object notation. you're looking{ opacity: x }
.- you need set css of elements when buttons pressed. omitting event callbacks, buttons don't anything. i've moved
$("#container").css({opacity: x});
inside callback functions.
now fixed:
$(document).ready(function() { var x = 0.5; $("#up").click(function(){ x += .2; $("#container").css({opacity: x}); }); $("#down").click(function(){ x -= .2; $("#container").css({opacity: x}); }); });
check out working demo here: jsfiddle
i recommend reading on javascript before diving jquery, you'll have better understanding of how language works.
Comments
Post a Comment