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!):

  1. var x = x += 0.2; not kind of assignment you're trying do. increments x 0.2, assigns new local variable x value of evaluated x. since x accessible scope of callback functions, use x += .2.
  2. { 'opacity', x } in css function argument not valid object notation. you're looking { opacity: x }.
  3. 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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -