Ish T.
Ish T.

Reputation: 11

How to change background color of divs on mouse click and drag with the HTML5 color input

I want to change the background color of my divs by clicking and dragging over them to the value of the color from the color input.

HTML:

<div class="center">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>

<div class="center" id="colorDiv">
  <input type="color" id="colorPicker">
</div>

Javascript:

var div = $('.square');
div.mousedown(function() {
  $(this).css("background-color", $("#colorPicker").val());
});

Here is my JS Fiddle
This is the effect I want but with the color value: JS Fiddle

Upvotes: 1

Views: 1112

Answers (3)

libra
libra

Reputation: 4331

This may be what you want.

var div = $('.square')
div.mousedown(function() {
    $(this).css("background-color", $("#colorPicker").val())
    div.mouseenter(function() {
        $(this).css("background-color", $("#colorPicker").val())
    })
})
$(document).mouseup(function() {
    div.off('mouseenter')
})

Upvotes: 0

Priyanka Choudhary
Priyanka Choudhary

Reputation: 37

<script type="text/javascript">
$(document).ready(function(){
    $('input').on('change', function() {
        var color = $("#colorPicker").val();
        $(".square").css("background-color", color);
    });
});
</script>
<div class="center">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

<div class="center" id="colorDiv">
<input type="color" id="colorPicker">
</div>

<style type="text/css">
.square
{
    width: 100%;
    height: 20%;
    float: left;
    position: absolute;
}
#colorPicker
{
    top: 20%;
    position: relative;
}
</style>

Upvotes: 0

Fernando Bravo Diaz
Fernando Bravo Diaz

Reputation: 579

Do this with your jQuery:

    var div = $('.square');
    div.mousedown(function() {
        $(this).css("background-color", $("#colorPicker").val());
        //add this line
        div.on("mouseenter.square",function(){
             $(this).css("background-color", $("#colorPicker").val());
        });
    });

Upvotes: 2

Related Questions