Kristaps Gaidulis
Kristaps Gaidulis

Reputation: 104

Highlighting selected list item using javascript

I know, this question is asked like milion times, but I cant get it to work.

All my html,css and js files are located in same folder.

Below - my code, but I also mad jsfiddle here .

The code works fine in JSfiddle, but doesnt work on my computer, so i thought it might be something with my html head and linking to javascript file, but it seems to be right.

header of my html file :

 <head>
   <title>Nacionālie dārgumi</title>
   <link rel="stylesheet" type="text/css" href="style.css">
   <script src="script.js"></script>
 </head>

This is my html:

<div class="menu">
        <ul class="main-menu">              
            <li><a class = "main_men_links" href="about.html">PAR PROJEKTU</a></li>
            <li><a class = "main_men_links" href="">NACIONĀLIE DĀRGUMI</a></li>
            <li><a class = "main_men_links" href="">SASNIEGUMI</a></li>
            <li><a class = "main_men_links" href="">SĀKUMS</a></li>
        </ul>   
    </div>

This is my script.js:

$(function(){
    console.log('ready');

    $('.main-menu li').click(function(e) {
        e.preventDefault()

        $that = $(this);

        $that.parent().find('li').removeClass('active');
        $that.addClass('active');
    });
})

This is my style.css :

.active {
    background: black;
}

Any help will be highly appreciated!

Upvotes: 0

Views: 188

Answers (4)

yadhu
yadhu

Reputation: 15632

You're using jQuery, so you need to provide the link to the library to get your script.js work. Make sure that the CDN library and your local script.js are added in this order.

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

in your browser Press F12 and check the tab Sources (in Chrome) or Debugger (in Firefox) to make sure script.js is loaded.

You must also see a 'ready' message in your browser console.

Upvotes: 0

Ajmal E S
Ajmal E S

Reputation: 57

Header should be loading jquery.

You can try as below :

<head>
   <title>Nacionalie dargumi</title>
   <link rel="stylesheet" type="text/css" href="style.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
   <script src="script.js"></script>
 </head>

or download jquery.min.js and load it.

Upvotes: 1

ruchira Shah
ruchira Shah

Reputation: 21

Please check whether you have included the reference of Jquery.js in your Header part of HTML or not. As , your script file will not run if you haven't use jquery.js before the script.js load .

Upvotes: 2

aldrien.h
aldrien.h

Reputation: 3615

I think you don't have jquery library on html head section. like this using CDN <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

Try to add before your main script declaration. This link only works if you are connected to internet, or download the file so you can use it locally.

Upvotes: 2

Related Questions