1

I am trying to change the background color of a panel using javascript to emulate "selected" functionality.

So, on click I get hold of the div by ID and change its background color.

It works fine but only momentarily and again resets the background color, and I have no idea why?

DJANGO HTML Template

<div class="panel-group">
    {% if articles %}
        {% for article in articles %}
            <div class="panel panel-success" id="aid_{{ article.articleId }}">
                 <div class="panel-body">
                    <a href="" onclick="populateArticle({{ article.articleId }})" style="font-size: 1.2em"><b>{{ article.title }}</b></a><br/>
                    <span style="color:darkgrey; font-size:.9em; font-family:sans-serif; font-style:italic">{{ article.source }} - {{ article.date }}</span><br/>
                    {{ article.sentences }}
                 </div>
            </div>
        {% endfor %}
    {% else %}
        NO ARTICLES PRESENT
    {% endif %}
</div>

Javascript

function populateArticle(aid) {
    document.getElementById('aid_'+aid).style.backgroundColor="#DEF1DE";
}

Also here is a link to a gif I recorded that shows the behavior: http://g.recordit.co/fSoTieo5Qn.gif (copy-paste the link in a new tab in case if it gives error).

Any ideas why this is happening?

The Wanderer
  • 3,051
  • 6
  • 29
  • 53

2 Answers2

1

You are not preventing default <a> tag behavior, so Your page refreshes.

onclick="populateArticle({{ article.articleId }});return false;"

Should fix it.

Bogdan Kuštan
  • 5,427
  • 1
  • 21
  • 30
  • Ahh Brilliant !!! That solves it. And now that you pointed it out, it reminded me on this great thread on javascript void(0) and why it is important to return false from onlick events: http://stackoverflow.com/questions/134845/href-attribute-for-javascript-links-or-javascriptvoid0 – The Wanderer Jun 21 '15 at 07:28
0

No idea why that may be happening, I personally would try this:

<script>
    $(document).ready(function () {
        $(".panel-body a").on("click", function (e) {
            e.preventDefault();
            var id = "#aid_" + $(this).attr("data-articleID");
            $(id).css("background-color", "#DEF1DE");
        });
    });
</script>

After your jQuery script and lose the onClick in your HTML (Bad practice) instead pass the id reference by adding a data-articleID attribute. Like this:

<a href="#" data-articleID="id23" style="font-size: 1.2em"><b>article title</b></a>

If your issue still persists you'd have to check for any other JavaScript changing the background back to original colors.