Md. Parvez Alam
Md. Parvez Alam

Reputation: 4596

D3js highlight bar one by one continuously

Here is the sample fiddle

Below code is to create bar

      svg.selectAll("rect")
   .data(dataset, key)
   .enter()
   .append("rect")
   .attr("x", function(d, i) {
        return xScale(i);
   })
   .attr("y", function(d) {
        return h - yScale(d.value);
   })
   .attr("width", xScale.rangeBand())
   .attr("height", function(d) {
        return yScale(d.value);
   })
   .attr("fill", function(d) {
        return "blue";
   })

    //Tooltip
    .on("mouseover", function(d) {
        d3.select(this).style("fill","red");
    })
    .on("mouseout", function() {
        d3.select(this).style("fill","blue");
    })  ;

On mouseover bar gets red color, and on mouseout it gets back to blue color,

I want it to continuously get red color one by one means first bar red then second bar, then third, after moving ahead previous bar should restore its origin color, there will be only one red bar at a time. and it should be like when it reach to end, it should again start from beginning

Upvotes: 0

Views: 210

Answers (3)

David Guan
David Guan

Reputation: 4300

Here is the result: http://jsfiddle.net/DavidGuan/f07wozud/4/

Code I added:

function reRenderColor() {
  svg.selectAll("rect")
      .transition()
      .delay(function(d, i){ return i* 500 })
      .duration(200)
      .style('fill', 'red')
      .transition()
      .delay(function(d, i){ return i* 500 + 400 })
      .duration(200)
      .style('fill', 'blue')
}  

reRenderColor();
setInterval(reRenderColor, svg.selectAll("rect").size() * 500 + 500)  

Upvotes: 3

J.Cheong
J.Cheong

Reputation: 227

Hope this is what you want

//Tooltip
.on("mouseover", function(d) {
    d3.selectAll("rect").style("fill","blue");
    d3.select(this).style("fill","red");
})
.on("mouseout", function() {
})  ;

fiddle

Upvotes: 0

eko
eko

Reputation: 40647

I gave .attr("id", function(d,i){return "rect"+i;}); to your rect elements in order to select them. Then, I used a recursive setTimout function to solve this with d3 transition property.

 var z = 0;
  var timeoutFunc = function(){ 
  setTimeout(function(){
    if(z < 20){
      d3.select("#rect"+ z).transition().duration(350).attr("fill","red")
                           .transition().delay(550).attr("fill","blue");       
      z++;
      timeoutFunc();
    }else if(z == 20){
        z = 0;
      timeoutFunc();
    }    
  },500);
  };

Here's an updated fiddle.

Note that durations could be changed for a better color visualization but this will give you an idea.

http://jsfiddle.net/51Lsj6ym/5/

Upvotes: 0

Related Questions