Rob
Rob

Reputation: 33

d3js timeline adding current month renders multiple rectangles and doesn't clear

I am putting together a timeline chart -- and I've tried to highlight the current month with a rectangle block that has an opacity.

https://jsfiddle.net/g89kuoe1/3/

    var date = new Date();
    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

    var currentMonth = itemRectsCurrentMonth
        .append('rect')
        .attr('class', 'currentMonth')
        //.selectAll('rect')
        .attr('x', function(d) {
            return x1(firstDay);
        })
        .attr('y', 0)
        .attr('width', function(d) {
            return x1(lastDay) - x1(firstDay);
        })
        .attr('height', function(d) {
            return y1(mainHeight);
        });

    /*
    currentMonth
        //.enter()
        .append('rect')
        .attr('class', 'currentMonth')
        .attr('x', function(d) {
            return x1(firstDay);
        })
        .attr('y', function(d) {
            return y1(mainHeight);
        })
        .attr('width', function(d) {
            return x1(lastDay) - x1(firstDay);
        })
        .attr('height', function(d) {
            return y1(mainHeight);
        })*/

    currentMonth.exit().remove();

-- this creates a blur effect

enter image description here

Upvotes: 0

Views: 82

Answers (1)

Rob
Rob

Reputation: 33

I've solved the problem by doing a remove first.

https://jsfiddle.net/a8ps1dk7/

    var date = new Date();
    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

    console.log("firstDay", firstDay);
    console.log("lastDay", lastDay);

    itemRectsCurrentMonth.selectAll(".currentMonth").remove();

    itemRectsCurrentMonth
        .append('rect')
        .attr('class', 'currentMonth')
        //.selectAll('rect')
        .attr('x', function(d) {
            return x1(firstDay);
        })
        .attr('y', 0)
        .attr('width', function(d) {
            return x1(lastDay) - x1(firstDay);
        })
        .attr('height', function(d) {
            return y1(mainHeight);
        });

Upvotes: 1

Related Questions