Reputation: 121
My code is meant to have a table which when clicked td will turn red. When clicked again the td will turn back to normal colour. I have got this to work with the code listed below. Next, I want to get it so that if the user has the mouse held down each td he hovers over will become red. I have no idea about how to go about this? Current code is :
<style>
.Selected{
background-color :red;
}
</style>
<script>
$(document).ready(function() {
$('#WeekTable td').live('click', 'td', function() {
$(this).toggleClass('Selected');
});
$('#Which').click(function() {
$('.Selected').each(function(index){
alert($(this).attr("ID"));
})
});
});
</script>
<table id="WeekTable" >
<tr id="WeekRow">
<td value = "1" id="Week1">1</td>
<td value = "2" id="Week2">2</td>
<td value = "3" id="Week3">3</td>
<td value = "4" id="Week4" >4</td>
<td value = "5" id="Week5">5</td>
<td value = "6" id="Week6">6</td>
<td value = "7" id="Week7">7</td>
<td value = "8" id="Week8">8</td>
<td value = "9" id="Week9">9</td>
<td value = "10" id="Week10">10</td>
<td value = "11" id="Week11">11</td>
<td value = "12" id="Week12">12</td>
<td value = "13" id="Week13">13</td>
<td value = "14" id="Week14">14</td>
<td value = "15" id="Week15">15</td>
</tr>
</table>
<button id="Which" >Which Weeks?</button>
Thanks guys!
Upvotes: 0
Views: 449
Reputation: 8765
Here's one way to go about it. You can use the mousedown
event with jQuery. Set a global boolean dragging
that's false
by default, and make it true
while the mouse button is held down, and back to false
when it's released:
$(document).ready(function() {
var dragging = false;
$('html').mousedown(function(e){
dragging = true;
})
$('html').mouseup(function(e){
dragging = false;
});
$('#WeekTable tr td').mouseover(function(e){
if (dragging) {
$(this).css('background-color', 'red');
}
});
});
Upvotes: 0
Reputation: 246
i would setup a variable that remembers if the mouse is currently held down or not.
mouseIsDown = false;
$(window).mousedown(function(){
mouseIsDown = true;
});
$(window).mouseup(function(){
mouseIsDown = false;
});
then use that variable in the td hover event callback
$("#WeekTable td").hover(function(){
if(mouseIsDown) $(this).addClass("Selected");
});
for the clicking you dont have to use live events , just do :
$("#WeekTable td").click(function(){
$(this).toggleClass('Selected');
});
Upvotes: 1