0

I have a Django project in which I have this HTML code in my template:

    <div class="upper_bar">
        <div></div>
        <div class="stats_bar">{{ stage1_total }} recibidos, {{ stage2_total }} en preparación, {{ stage3_total }} en camino y {{ stage4_total }} entregados</div>
        <div id="createButton" onclick="myFunction()"><i class="fas fa-plus-circle" style="font-size:48px;"></i></div>
    </div>

In my scripts tag, I have this:

function myFunction()
{
    alert('Function...');
}

I previously had this code instead in my scripts:

document.getElementById('createButton').addEventListener('click',
    function()
    {
        alert('message...');
        document.querySelector('.bg-modal').style.display = 'flex';
    }
);

But it didn't work either. Does someone know why is the div called 'createButton' not working? I don't want to use a button since I'd like to only see the icon, or is there another way to just see the icon in a way that works and calls the function?

Michael Hawkins
  • 2,528
  • 16
  • 29
  • Definitely keep the version you had before (`addEventListener`). It's way cleaner to separate HTML from JS. But for it to work, you need `#createButton` to already exist. I'm just guessing here, but is your script defined in the `` tag? If it is, then the DOM is not complete yet. Either move your ` – blex Jun 24 '20 at 22:23
  • If that does not work (and actually, every time you are developping), open your browser's developer console, it will tell you what errors occurred, and where they originated from – blex Jun 24 '20 at 22:30
  • Thanks! That was it, I had to place the script section right at the end of the body tag. The template inherits from another, so I didn't know where the scripts where being included into, and I just moved them and it works now. Thanks a lot. – Iván Flores Vázquez Jun 24 '20 at 22:39
  • https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – epascarello Jun 24 '20 at 22:59

1 Answers1

0

Your div element that is the target is empty - not even blank space. Adding some content seems to work fine: https://jsfiddle.net/0fkyp5nj/

HTML:

 <div class="upper_bar">
        <div></div>
        <div class="stats_bar">{{ stage1_total }} recibidos, {{ stage2_total }} en preparación, {{ stage3_total }} en camino y {{ stage4_total }} entregados</div>
        <div id="createButton" onclick="myFunction()"><i class="fas fa-plus-circle" style="font-size:48px;"></i>test 123</div>
    </div>

JavaScript:

function myFunction()
{
    alert('Function...');
}
Michael Hawkins
  • 2,528
  • 16
  • 29