0

apologies by the way, i have never touched jquery before so i have no idea what i am doing.

i am trying to add a bit of jquery code in my html page, i cannot really paste the entire page, but essentially i have this block contained in section:

  <script defer src="script.js"></script>
  <script>
    $('a').hover(function() {
        $(this).css('color', 'green');
    }, function() {
        $(this).css('color', 'black');
        }
    );
    window.onload=function(){
    }
  </script>

however, the links on my page does not reflect the hover effects changes i wrote here

what could i be doing wrong? and please let me know if the entire page has be posted in order for any sort of troubleshooting...

EDIT: okay I have made a test page, there isn't much on it, but the jquery commands still does not work here:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <title>Test Page</title>
    <script>
    $('a').hover(function() {
        $(this).css('color', 'green');
    }, function() {
        $(this).css('color', 'black');
        }
    );
    </script>
</head>
<body>
    <h1 id="headingOne">Header 1</h1>

    <a href="google.com">Link 1</a>
    <a href="google.com">Link 2</a>
    <a href="google.com">Link 3</a>
</body>
</html>

PS: i understand that it is not necessary to be using javascript/jquery for any of this, but this is for a school assignment and it says to be using jquery for this task...

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
user3696118
  • 343
  • 3
  • 17

6 Answers6

2

This is the way you should do it if you want to do it with jQuery and not CSS:

$("a").on("mouseover", function() {
  $(this).css("color", "green");
}).on("mouseout", function() {
  $(this).css("color", "black");
});
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>

<a href="#">Hover on me!</a>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • thank you! but this looks like the code is supposed to be in a separate .js file. how could i make it so that it works in the formatting as i have listed? all in one html file..? – user3696118 Oct 08 '18 at 01:51
  • @user3696118 Just replace the code you currently have, I just modified it to make it work. – Jack Bashford Oct 08 '18 at 02:28
2

I have made you a basic example where this is working, i hope it help you.

$(document).ready(function()
{
    // Register hover listener on anchor tags.

    $('a').hover(function()
    {
        $(this).css('color', 'green');
    }, function()
    {
        $(this).css('color', 'black');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a>JUST A LINK</a>
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • Hi there, thank you so much for the example. is this by the way intended to be stored in a separate .js file? my understanding of jquery was that one of the advantages is that it can be embedded right in the HTML file, how would you achieve that? – user3696118 Oct 08 '18 at 01:38
  • You can use javascript code enclosed on `` tags on the HTML page, this same is valid for JQuery too. The "snippet tool" separates the code in differents sections but this is not neccesary. – Shidersz Oct 08 '18 at 01:44
  • but why then is the example that i listed not working? is it because it is missing the $(document).ready(function) section? – user3696118 Oct 08 '18 at 01:48
  • I don't believe is not working for that, just see your update. Check the developer console in case there is any error. – Shidersz Oct 08 '18 at 01:58
2

You don't need Javascript for such a simple problem. You can just use the :hover CSS pseudo class.

.myClass{
  color: black;
}
.myClass:hover{
  color: green;
}
<a class="myClass">This is a link</a>

If you must use jQuery, you can use the .hover() function with the first argument being the function to execute on hover and the second argument being the function to execute when the element is no longer hovered over.

$(function(){
  $('.myClass').hover(function(){
  $(this).css('color', 'green');
  }, function(){
  $(this).css('color', '');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="myClass">This is a link</a>

Your example does not work because you are trying to access the DOM before it is ready. You should add event listeners inside $(document).ready(function(){}) or equivalently, $(function(){}). Working example with your code (http://jsfiddle.net/oe6m38xj/):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <title>Test Page</title>
    <script>
    $(function(){
        $('a').hover(function() {
        $(this).css('color', 'green');
    }, function() {
        $(this).css('color', 'black');
        }
    );
    })
    </script>
</head>
<body>
    <h1 id="headingOne">Header 1</h1>

    <a href="google.com">Link 1</a>
    <a href="google.com">Link 2</a>
    <a href="google.com">Link 3</a>
</body>
</html>

If you want to listen for all hover events on dynamically created a elements you can listen to hover events on the document that match "a" (that is, being an anchor element).

   <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
        <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <title>Test Page</title>
        <script>
        $(document).on('mouseenter', 'a', function() {
            $(this).css('color', 'green');
        }).on('mouseout', 'a', function() {
            $(this).css('color', 'black');
        });
        </script>
    </head>
    <body>
        <h1 id="headingOne">Header 1</h1>

        <a href="google.com">Link 1</a>
        <a href="google.com">Link 2</a>
        <a href="google.com">Link 3</a>
    </body>
    </html>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • yes, i am sure it is not necessary to be using jquery, but its for a school assignment so we are told to use it – user3696118 Oct 08 '18 at 02:46
  • 1
    Definitely this. If it’s for a school assignment as a simple example then okay, but please in the real world later in life, don’t use JavaScript at all for a simple hover effect. (There are people who do, and it’s not using the right tool for the job.) CSS has a lot of power to it and a lot of people on StackOverflow look to JavaScript for everything, when they should use more CSS. – Nate Oct 08 '18 at 03:19
  • @user3696118 I have added working examples with your code. – Unmitigated Oct 10 '18 at 03:13
1

$(".selector").on({
    mouseenter: function () {
         $(this).css("color", "red");
    },
    mouseleave: function () {
         $(this).css("color", "");
    }
});
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>

<a class="selector" href="#">Hover on me!</a>
user-9725874
  • 831
  • 9
  • 15
1

The $('a') operator finds all the anchor elements in the DOM and applies what follows to them. Because you have your code running synchronously in the head of your HTML document, there are no anchor elements in the DOM at the time that code runs. In order to apply your hover code to the anchor elements in the page, you have to wait until after the anchor elements are created. You can do this by putting your code inside $(document).ready(function() { /*put your code here*/ }) which will wait to execute your code until all the DOM elements are added to the DOM.

Out of necessity, this site's sandbox that enables the "Run code snippet" functionality obscures these kind of initialization problems because of all work it has to do to get the snippets to work safely inside an existing page.

Using the CSS hover pseudo-class would be better for this example as it would not have this problem (it would affect all anchor elements on the page even if they are added later), but you would still want to use jQuery if the action you are triggering is not something that can be handled via CSS (for example, if you wanted to pause playing a video in response to the hover).

Old Pro
  • 24,624
  • 7
  • 58
  • 106
  • hmmmm i see, so this is sort of like the "window.onload" code that you add into you HTML page? if that is the case, then what is the reasoning for using the jquery syntax? isnt it not better to just stick to the regular javascript syntax and keep everything separate (HTML/js)? – user3696118 Oct 08 '18 at 02:08
1



Can i add jQuery inside the HTML page?

You can add your jQuery code in the page. But adding at the bottom (just before the </html> close tag) will be good.

see this:- Should Jquery code go in header or footer?

Why click function is not working?

You have to add click inside <ready> function, for some reasons with DOM you will have to think about some another approch for click event. see this



Can i add jQuery inside the HTML page?

Why is this jQuery click function not working?

saifudeen ni
  • 145
  • 9