toggleClass doesn't work

Started by Sir Osis of Liver, October 11, 2020, 07:43:11 PM

Previous topic - Next topic

Sir Osis of Liver

Copied from JSFiddle, works there but not for me. >:(



<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$("td").click(function() {
    $(this).toggleClass("focus");
    });
</script>
<style>
td {
    border-style:solid;
    border-width:medium;
    border-color:red;
    padding: 5px;
}
.focus
{
    background: yellow;
}
</style>
</head>
<body>
<table>
    <tr>
        <td>cell 1</td><td>cell 2</td>
    </tr>
    <tr>
        <td>cell 3</td><td>cell 4</td>
    </tr>
</table>

</body>
</html>


When in Emor, do as the Snamors.
                              - D. Lister

live627

Try to add the JavaScript to the end of your document

Sir Osis of Liver

Why does that work, but not at top?
When in Emor, do as the Snamors.
                              - D. Lister

Arantor

Because at the time that code runs, the tds don't exist yet.

Literally that's as far as the page got - was to your script tag. When it runs at the end of the document, the tds exist at that point.

This is also what $(document).ready({ ... }) is all about - run the code once the page has loaded.
Holder of controversial views, all of which my own.


Sir Osis of Liver

Will have to think about that.  I have js/jq running in <head> in some other scripts, must be sequence is different.  But it works, thanks. :)
When in Emor, do as the Snamors.
                              - D. Lister

Arantor

Stuff that lives in <head> can work if it's wrapped in $(document).ready(), which says 'wait until the page is done loading before running the code...
Holder of controversial views, all of which my own.


Sir Osis of Liver

Not working for me.  Brackets?



<head>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script>
$(document).ready({
$("td").click(function() {
    $('*').removeClass('focus');
    $(this).toggleClass("focus");
    });
});
</script>


When in Emor, do as the Snamors.
                              - D. Lister

Arantor


<head>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script>
$(document).ready(function(){
    $("td").click(function() {
        $('td.focus').removeClass('focus');
        $(this).addClass("focus");
    });
});
</script>


If you're already removing focus from all the relevant things, no point in a) tagging literally every single tag on the page and b) setting to toggle when you already know the outcome must be addition.
Holder of controversial views, all of which my own.


Sir Osis of Liver

When in Emor, do as the Snamors.
                              - D. Lister

Advertisement: