Adjusting the background hue of a bootstrap panel

I'm attempting to utilize JavaScript to change the background color of a panel in order to create a "selected" effect.

Upon clicking, I retrieve the div by its ID and modify its background color.

Although it initially works as intended, the background color reverts back almost immediately, and I'm unsure why this is occurring.

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";
}

Here is a link to a gif demonstrating the issue: (copy-paste the link in a new tab if it gives an error).

Any insight into why this behavior is happening would be greatly appreciated.

Answer №1

The <a> tag default behavior is not being prevented, leading to your page refreshing.

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

Implementing this fix should resolve the issue.

Answer №2

I can't figure out why this is happening, but personally, I would suggest trying the following solution:

<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>

Instead of using onClick in your HTML (which is not good practice), try passing the id reference by adding a data-articleID attribute to your link like this:

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

If the issue persists, you may need to investigate whether any other JavaScript code is reverting the background color to its original state.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a callback function within its own definition

I need help with my download function that is calling a callback to "downloadCallback". Is it possible to define the downloadCallback function inside the download function itself? If so, how can I achieve this? Below is the implementation of the download ...

What is the method for implementing a dropdown box with select and non-select checkboxes, similar to the example shown in the image, using AngularJS?

https://i.sstatic.net/CTx8K.jpg I am seeking assistance in incorporating the image below into a dropdown menu using angularjs ...

What is the best way to centrally position a <mat-card> on the screen using Angular 9?

* I'm struggling to center a <mat-card> on the screen, specifically within the toggle-device-toolbar. It's intended for mobile phones and I could use some guidance. I'm working with angular-material and ng-bootstrap* Here is the code ...

Unleashing the power of storytelling with React: A guide to creating dynamic story

weather.stories.ts export default { title: 'Widgets/Forecast', component: Weather, } const Template: Story<any> = (args) => <Weather {...args} />; export const Default = Template.bind({}); Default.args = { forecast: { ...

Changing the color of tabs using inline styles in material ui does not seem to work

I am brand new to using material ui and have been attempting to alter the colors of the selected tab. Currently, the color is a dark blue shade and I am aiming to change it to red. I tried applying inline styles, but unfortunately, there was no change. C ...

Softening the edges of a table

Could you assist me in rounding the corners of my table? I attempted using the basic border-radius, however, it only separated the border at the corners. Do you think this issue is due to my browser (Firefox) or could it be a bug? You can view my Jsfiddl ...

Calculate the difference in days between two selected dates from an Ajax Datetime Picker using JavaScript

How can I use JavaScript to count the number of days between two selected dates from Ajax date time pickers in my aspx page? The script should automatically input this calculated value into a designated "Number_Of_Days" text box without requiring a page ...

What is causing onbeforeunload to consistently display a dialog box?

I'm facing an issue where my javascript code displays a confirmation dialog even when there is no unsaved data. I have simplified the problem to this bare minimum: window.addEventListener("beforeunload", (e) => { e.returnValue = null; retu ...

Can side effects be safely incorporated within the callback of the useState hook?

Consider this scenario: const [value, setValue] = useState(false); const setSomething = (val) => { setValue((prev) => { fn(); dispatch(action); // or any other side effect return prev + val; }); }; Is it acceptable and in line with ...

JavaScript alert causing disruption to Ajax requests

Currently, I am utilizing JQuery Ajax to retrieve a script from the server. $.ajax({ url: src, type: "GET", dataType: "script", timeout: transaction_timeout }).done(function(){}) .fail(function() { alert("Error in server");}) .always(funct ...

The progress bar in Next JS 13 seems to be malfunctioning and is not displaying any

After transitioning to the new Next JS 13 app directory, I encountered an issue where the progress bar at the top does not function when the page loads. In the previous version, Next JS 12, there was a package named nprogress and nextNprogress that simpli ...

Retrieving HTML table data using PHP

In the scenario where I have an HTML form with a table like the one below: <form method="POST" action="a.php"> <table name="dataTable"> <tr> <td>row one col one</td> <td>row one col two</td> <td>row o ...

Is it possible to initiate an animation in a child component using an input variable?

I have a specific animation that I would like to trigger once an *ngFor loop completes ngAfterViewInit(): void { this.items.changes.subscribe(() =>{ Promise.resolve().then(() => { this.everythingLoaded(); }) }) } After the loop fini ...

Achieving perfect alignment for a div that can adapt to different sizes and

Struggling with my CSS skills, I have spent countless hours trying to center a fixed/dynamic size div. The setup involves multiple images within a 100x100 size frame. Upon clicking on an image (thanks to jQuery), #fade is triggered to reveal a window showc ...

Automatically close one option upon opening another

Displayed below is the HTML code that I have printed with echo: <input id="58" readonly="readonly" class="cell_to_edit" value="Accepted"> <span id="58" class="toggle_status"> <select class="status_change"> <option>Ac ...

"Exploring the functionality of Vue JS2 checkboxes within a parent and

I am working with a complex nested list structure: <ul> <li v-for="subregion in continents"> <input type="checkbox" :id="subregion[0].subregion" > <label :for="subregion[0].subregion">{{ subregion[0].subregion }}< ...

"Integrating backgrounds into divs disrupts the overall design aesthetic

One of the challenges I faced was trying to space out the three columns in my Bootstrap row while also splitting each column into two parts. After doing some research, here's the solution I came up with: <div class="container row h-100 mx-auto ...

What is the best way to change the background color of a table cell in HTML and CSS?

Trying to adjust the background image of each data cell to a selected image has been challenging. Using the method displayed below, only the top left corner of the photo appears. The code snippet demonstrates setting the background of each data cell to th ...

What is the method for configuring the asp-for input tag helper to create camelCase names?

My view model is structured as follows: public class MyModel{ public DateTime? StartDate {get;set;} } When using an input tag on a view with the asp-for tag helper, the default HTML generated looks like this: <input type="datetime" id="StartD ...

Tips for creating a clickable phone number on a WordPress classified website

Despite trying numerous solutions to make the phone number clickable, it still didn't work as expected <?php global $redux_demo;?> <?php $phoneon= $redux_demo['phoneon']; ?> <?php if($phoneon == 1){?> <?php $po ...