Search code examples
jqueryeventslive

Tie live changes to element CSS as it is changed?


Wasn't sure how to word that title, but I'm wondering how I can tie element styling changes to an event (such as a slider) to show the effect as it is happening...

Example 1: if I have a slider to change the opacity of a div, how would I 1) create a slider that starts at 0 and ends at 1 in regards to the elements opacity, and 2) watch the slider's position and change the element's opacity as it is dragged back and forth?

Example 2: if I have a colour map to set an element's background colour, how would I 1) get the hex of the colour that the cursor is over, and 2) watch the cursor as it moves over the colour map and live change the element's colour as it moves across the map?


Solution

  • Using Javascript/JQuery, you can bind a function to an event. For example, you could use the JQuery slider and simply bind a function to its change event and have the function modify the element's opacity like so:

    $("sliderElement").slider({
        change: function(event, ui){
            $("opacityElement").css('opacity', ui.value);
        }
    }
    

    Whenever you change an element's CSS style the browser will repaint it. So just use javascript to change its style attribute whenever you need to change the look.