1

I found other related questions but none of the answers there actually fixed my problem. The button works fine on IE, but not on Chrome. I tried removing the span element, putting the button outside any other tags, and still fires twice. This temple extends a 'base.html' file and the code is inside a 'main' element.

HTML:

<div class="jumbotron p-4">
<div class="container-fluid">
    <h1 class="jumbotron-heading">{{ category.name }}</h1>
    <div>
        <strong id="like_count">{{ category.likes }}</strong> likes
        {% if user.is_authenticated %}
        <button id="like_btn" data-categoryid="{{ category.id }}" class="btn btn-primary btn-sm" type="button">
            <span data-feather="thumbs-up"></span>
            Like Category
        </button>
        {% endif %}
    </div>
</div>

JQuery:

$(document).ready(function() {
    $('#like_btn').click(function() {
          alert('button clicked');
        });
});
1nfern0
  • 147
  • 1
  • 6
  • 1
    You could try to add a `console.log('ready'):` just after the ready function to check if this is fired twice. I was not able to reproduce your issue. I have the suspicion, that somehow this script is included twice. – Moritz 'e1mo' Fromm Mar 31 '21 at 14:55
  • I think the same as @Moritz because I created a fiddle with your code ( https://jsfiddle.net/2a18n6yz/ ) but it works for me. Search if you have 2 click events in your inspector. – Ichinator Mar 31 '21 at 14:58
  • @Moriiz Thank you. This actually helped me solve the problem as Chrome dev tools don't show if a script loads twice. I'm following a tutorial that claims adding the scripts at the end of the body helps pages load faster. I found this [question](https://stackoverflow.com/questions/20825642/why-javascript-files-are-loading-twice-console-log-and-alert-and-jquery-click/20825823) So I moved the scripts in the head and this fixed the problem. – 1nfern0 Mar 31 '21 at 16:54

1 Answers1

1

Use the chrome dev tools to check if you are loading your script or jquery twice. I'm not sure about chrome, but in Firefox dev tools you will be able to see if the event is being applied to the element twice by inspecting the element directly.

If you are compiling your script, check that the scripts aren't being duplicated during compilation.

Also, you can probably set your click event outside of the ready function. If that solves it, it's likely that jQuery is being loaded twice.

Bread
  • 11
  • 1