-3

I have this piece of code, but it has the problem

$ is not defined

This is the code below. I'm trying to adjust the font-weight according to window size

<!DOCTYPE html>
<html>

    <head>
        <style>
        .bold {
            font-weight: bold;
        }

        .normal {
            font-weight: normal;
        }
        </style>
    </head>

    <body>
        <div id="test" class="normal">hiiiii</div>
        <script>
        $(window).on('resize', function() {
            if ($(window).width() > 300) {
                $('#test').addClass('normal');
                $('#test').removeClass('bold');
            } else {
                $('#test').addClass('bold');
                $('#test').removeClass('normal');
            }
        })
        </script>
    </body>

</html>
Lokesh Yadav
  • 1,489
  • 3
  • 20
  • 48
Yiyue Wang
  • 142
  • 11

1 Answers1

1

$ functions is the part of jQuery library.

jQuery solution

If you want to use it in your project, you need to import it. You can either download this file or use Google CDN. The second one if preferable. Add this line in the head section before your functions:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

JS solution

You can also change your code to vanilla JS to achieve the same results if you don't want to use jQuery.

window.onresize = function() {
    var element = document.getElementById('test');
    if (window.width > 300) 
    {
        element.classList.add('normal');
        element.classList.remove('bold');
    } 
    else 
    {
        element.classList.add('bold');
        element.classList.remove('normal');
    }
};

CSS solution

However, as it seems to me, you don't need JS here at all.
It looks like you want to make text bolder if the window is less than 300px wide.

You can achieve this using CSS3:

#test {
    // Any properties
    font-weight: normal;
}

@media (max-width: 300px)
{
    #test {
        font-weight: bold;
    }
}

If the viewport width will become less than 300, then #test will become normal.

Yeldar Kurmangaliyev
  • 30,498
  • 11
  • 53
  • 87