How can I modify the border color within a div element?

My journey into web development is just beginning, and I've grasped the basics of Java, JSP, HTML, JS, CSS, and JQ. However, I've hit a roadblock while attempting to change the border color of a div upon mouse hover. Despite my efforts, I haven't been successful in achieving this effect. Below is the code snippet in question - any guidance on where I might be going wrong would be greatly appreciated. Thank you!

P.S: While I've scoured countless Stack Overflow questions and answers for a solution, I still find myself unable to crack this challenge. That's why I decided to pose my own query along with the relevant code, seeking suggestions for improvement moving forward. Thanks in advance.

<div id="navBar" style="height: 50px; width: 480px;">
            <div id="homeButton" style="float: left; color: #73C20E; position:relative; width: 160px; height: 50px; border-top: 4px solid #73C20E;">
                <p>Home</p>
            </div>
            <div id="siteAdminButton" style="float: left; color: #73C20E;  position: relative; width: 160px; height: 50px; border-top: 4px solid #1C1C1C;" >
                <p>Site Administration</p>
            </div>
            <div id="contactButton" style="float: left; color: #73C20E;  width: 160px; height: 50px; border-top: 4px solid #1C1C1C;">
                <p>Contact Us</p>
            </div>                    
</div>

Heres JS:

$("document").ready(function (){
    $("#homeButton").mouseenter(function (){
        $(this).addClass("mouseOverNav");
    }).mouseleave(function (){
        $(this).removeClass("mouseOverNav");
    });  

    $("#siteAdminButton").mouseenter(function (){
        $(this).addClass("mouseOverNav");
    }).mouseleave(function (){
        $(this).removeClass("mouseOverNav");
    });

    $("#contactButton").mouseenter(function (){
        $(this).addClass("mouseOverNav");
    }).mouseleave(function (){
        $(this).removeClass("mouseOverNav");
    });
});          

and here is css:

.mouseOverNav {
   cursor: pointer;   
   border-color: #73C20E;
}

Summary: I have created 3 divs with borders, 2 of which have the same border color as background, I want to change border color to my theme whenever mouse hovers, and change it back to the background color when mouse leaves and make the cursor a Pointer.

So far: Pointer Cursor is working but its not changing the border color. Thanks in Advance.

Answer №1

To make your selectors more concise, you can use the following code:

$("document").ready(function () {
    $("#homeButton, #siteAdminButton, #contactButton").mouseenter(function () {
        $(this).addClass("mouseOverNav");
    }).mouseleave(function () {
        $(this).removeClass("mouseOverNav");
    });
});

Since you have set inline style border-top: 4px solid #1C1C1C; in your HTML, ensure that you also include border-top style for .mouseOverNav in your external CSS file.

It is necessary to add the !important property to override the existing style as inline styles take precedence over external styles:

.mouseOverNav {
   cursor: pointer;   
   border-top: 4px solid #73C20E !important;
}

Check out the Fiddle Demo here!


Note: While the above solution works, it is advisable to avoid using !important unnecessarily, as mentioned in the MDN documentation:

When an !important rule is used on a style declaration, this declaration overrides any other declaration made in the CSS, regardless of specificity. However, using !important is not recommended because it disrupts the natural cascading of stylesheets and can make debugging difficult.

In such cases, you can move all inline styles to an external CSS file like this:

#homeButton, #siteAdminButton, #contactButton {
    float: left;
    color: #73C20E;
    position:relative;
    width: 160px;
    height: 50px;
    border-top: 4px solid #73C20E;
}
#siteAdminButton, #contactButton {
    border-top: 4px solid #1C1C1C;
}

#navBar .mouseOverNav {
    cursor: pointer;
    border-top: 4px solid #73C20E;
}

View the updated Fiddle Demo!

You can also achieve the same result using the :hover selector in CSS:

#homeButton:hover, #siteAdminButton:hover, #contactButton:hover{
   cursor: pointer;   
   border-top: 4px solid #73C20E;
}

See the alternative approach in the Fiddle Demo!

Answer №2

ACHIEVING THIS EFFECT IS EASY WITH CSS USING THE :hover PSEUDO-CLASS. YOU DON'T NEED TO USE JAVASCRIPT OR JQUERY

To implement this in CSS, you can do the following:

#homeButton:hover, #siteAdminButton:hover, #contactButton:hover{
   cursor: pointer;   
   border-color: #73C20E !important;
}

CHECK OUT THIS JSFIDDLE DEMO

Answer №3

You can achieve your desired outcome with just CSS, eliminating the need for JavaScript completely.

#navBar > div:hover{
   cursor: pointer;   
   border-color: #73C20E!important;
}

Answer №4

Take a look at this JSFiddle in action with your scenario: http://jsfiddle.net/g6Jf2/

.mouseOverNav {
   cursor: pointer;   
   border: 1px solid #73C20E;
}

Answer №5

Update your CSS styling

.mouseOverNav {
   cursor: pointer;   
   border-top: 4px solid #73C20E !important;
}

See the updated code on this link

I recommend using the hover function instead of mouse enter and leave for better performance

$("document").ready(function (){
    $("#homeButton, #siteAdminButton, #contactButton").hover(function (){
        $(this).toggleClass("mouseOverNav");
    });
}); 

Check out the improved version on this fiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Widen Textbox Sideways

I recently came across a JQuery plugin that caught my eye: https://github.com/rotundasoftware/jquery.autogrow-textarea After following the provided guide, I found myself stuck without any results. I attempted to implement it within my document.ready() $( ...

Safari iOS does not properly support responsive images when using srcset and sizes

I am facing an issue with the following code snippet: <img src="/img/footer/logo_white.png?v=2.0" srcset="/img/footer/logo_white.png?v=2.0 1x, /img/footer/logo_white2x.png?v=2.0 2x" > This ...

Guide to defining the encoding of an XML file with JavaScript

Hi there, I am currently facing an issue with encoding while creating a document using JavaScript. The problem is that the document rejects all non-ascii characters. For example, when passing the string "verificación", it gets replaced by "". Any suggesti ...

Preserving the Selected Date on the Calendar Even After the PHP Variable is Passed

I am currently using the calendar code below with a slight modification that I implemented. However, I have encountered an issue where when I select a date, the calendar successfully highlights the selected date. But once I pass this selected date along ...

Running a PHP function within a PHP environment

After the user clicks the submit button and no errors are present, a token value input is generated in the script below. The goal is to post this value inside a php page for use in a query. While the input value is successfully generated, posting it to the ...

Exploring the Battle of Efficiency: Stateless Components vs. Class Components in the Age of React Hooks - Determining the Superior Approach

Having delved into various online resources and discussions on platforms like Stack Overflow (link here), the consensus seems to lean towards utilizing stateless functions (functional components) whenever possible. Many of the life cycle methods found in ...

Querying through a database containing 1 million <string Name, int score> pairs efficiently within sub-linear time

My JSON object holds 1 million pairs. var student = {[ { name: "govi", score: "65" }, { name: "dharti", score: "80" }, { name: "Akash", score: "75" },............. up to a million ...

Tips on converting deeply nested JSON into an excel file using Node.js

I am attempting to convert the JSON data below into an Excel file using XLSX. Although it successfully converts my JSON to Excel, I encountered an issue where the nested array of dailyPointsArray appears blank after conversion. Code Attempted const XLSX ...

What is the method for accessing a selector within a foreach loop?

Whenever a user clicks on a date in the jquery datepicker, two ajax calls are triggered. The goal is for the second ajax call to populate the response/data into a paragraph with the class spots within the first ajax call, displaying available spots for th ...

Having trouble retrieving values for jVectorMap? The getElementById method doesn't seem to be functioning as

I have been trying to set markers on a jVectormap. I retrieve the content from my database and store it in a hidden input field. The format of the data is as follows: {latLng:[52.5200066,13.404954],name:'Berlin'},{latLng:[53.0792962,8.8016937],n ...

When hovering over nav bar links, shadows are not displayed

When hovering over the navbar links, I am able to change their color but a shadow at the bottom is missing. Is there a way to add a shadow at the bottom like it had before when not hovered? Visit this link for more information ...

Question: How can I use the jQuery datepicker to ensure that the selected date remains in the

I recently created a webpage using a combination of HTML, PHP, and jQuery. The PHP script is designed to load all data where the date matches the one selected in the text input field generated by the jQuery datepicker. However, I encountered a problem whe ...

Is it possible to import files in Vue JavaScript?

I want to incorporate mathematical symbols from strings extracted from a JSON file. While it seems to work perfectly on this example, unfortunately, I encountered an issue when trying it on my own machine. The error message 'Uncaught (in promise) Refe ...

Utilize CamelCase in jQuery for Better Code Readability

Upon examining the jQuery source code, I noticed an interesting use of camelcase: camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } // where: rmsPrefix = /^-ms-/, rdashAlpha = /-([\da- ...

Is it possible to import a component from a production build of create-react-app?

Has anyone tried importing a component from a production build of create-react-app? Situation: I have one CRA project that has been built for production. Inside this project, there is a component named ExampleButton. Now, I am working on a second CRA pro ...

Unable to obtain the necessary data during an AJAX insert operation

I have been using AJAX to insert data successfully. However, when I added the required attribute to input fields and select options, it doesn't seem to work. Is there something wrong with my code? <form role="form" id="form-add" class="form-horiz ...

Steps to send parameters to external web service in MVC3

A webservice functions in the following way: I captured this information within a partialview. <form action="www.xyz/x/y" method="post"> <input type="hidden" name="abc" value="40" /> <input type="button" id="btn"/> /> Upon cl ...

Storing images in MongoDB using React.js

I'm currently facing an issue with uploading an image file from the client side to MongoDB. To achieve this, I am utilizing an Express server along with 'multer' and 'sharp' for image uploading. On the client side, I have a CRA a ...

unable to execute grunt post npm installation

I'm having trouble getting grunt to work on my system. I tried installing it using npm install grunt -g It appears to have installed successfully - <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b3a6a1baa094e4fa0bbe7 ...

Organizing your thoughts: Utilizing Etherpad-Lite's list

Looking to stylize the list items with decimal, upper-alpha, lower-alpha, upper-roman, and lower-roman for each of the first five levels? I attempted to achieve this by adding CSS in my pad.css file. .list-number1 li:before { content: counter(first)") " ...