Transforming the navigation menu using CSS, HTML, and jQuery

One challenge I am facing involves creating a menu similar to the one on http://edition.cnn.com/.

I want the clicked button in the menu to receive focus, while the others lose it. Despite trying various methods, I have not been successful. Can someone offer guidance on how to accomplish this?

Another approach I considered: Putting focus in Html.ActionLink menu

Specifically, I wish for the selected button to retain focus after clicking, even after refreshing the page, with other buttons returning to their normal state or reverting back if previously selected.

Any suggestions would be greatly appreciated. Thank you.

Answer №1

CHECK OUT THE FIDDLE DEMO!

Hopefully this solution works for you!

$(function(){
    var jqMenu = $("#nav_menu").menu();

    $("#btn1").click(function(){
        try{
            jqMenu.menu( "focus", null, jqMenu.find("#item1"));
        }
        catch(exc){
            alert("An error occurred: "+exc);
        }
    });
    $("#btn2").click(function(){
        try{
            jqMenu.menu( "focus", null, jqMenu.find("#item2"));
        }
        catch(exc){
            alert("An error occurred: "+exc);
        }
    });
    $("#btn3").click(function(){
        try{
            jqMenu.menu( "focus", null, jqMenu.find("#item3"));
        }
        catch(exc){
            alert("An error occurred: "+exc);
        }
    });
});

Answer №2

It's possible that I may not be completely correct, but it seems like this is what you're referring to...

If your navigation menu is structured as a list, it would look something like this:

<ul>
    <li><a href="default.asp">Home</a></li>
    <li><a href="news.asp">News</a></li>
    <li><a href="contact.asp">Contact</a></li>
    <li><a href="about.asp">About</a></li>
</ul>

To style these links, you can use the following CSS:

a:link {color:#FF0000;}      /* unvisited link */
a:visited {color:#00FF00;}  /* visited link */
a:hover {color:#FF00FF;}  /* mouse over link */
a:active {color:#0000FF;}  /* selected link */ 

If you want to change the style of the entire list item, you can do so like this:

li {
    background-color: green;
}

For more tutorials on styling links, you can visit W3 Schools.

Answer №3

Your question lacks clarity, so let's take a stab at interpreting it:

Here is an example of the code that you might be looking for:

<nav>
    <ul>
        <li>Button 1</li>
        <li>Button 2</li>
        <li>Button 3</li>
    </ul>
</nav>

For Javascript (assuming you are using jquery):

$(function() {
    $("nav ul li").click(function() {
        $("nav ul li").not(this).removeClass("active");
        $(this).addClass("active");
    });
});

And here is some sample CSS to go along with it:

nav ul { list-style-type: none; }
nav ul li { float: left; cursor: pointer; padding: 10px; background-color: #eee; }
nav ul li.active { background-color: red; color: white; }
nav ul li:hover:not(.active) { background-color: #ccc; }

You can view a working demo on jsfiddle here: http://jsfiddle.net/6UdkD/1/

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

"Enhancing Code Functionality in React - Seeking Ways to Improve

When working with Redux, I often find myself repeatedly using the same piece of code: const dispatch = useDispatch() Then, every time I need to call a function, I do something like this: dispatch(endpointError(true)) My goal is to streamline this proce ...

Text flickering unexpectedly during hover animation in Bootstrap

Encountered a peculiar issue where dark colors flicker during animation. Link to codepen Adding -webkit-backface-visibility: hidden partially resolves the problem, but it also affects font appearance by making it tighter and brighter. This issue is obser ...

Guidelines on Transferring Variables to a JavascriptExecutor Script

Currently, I am utilizing C# and Selenium to browse through a website and have come across an issue regarding passing variables into my JavaScriptExecutor command. When I attempt to do so using the code below: ((IJavaScriptExecutor)webdriver).ExecuteScript ...

Reduce XSLTProcessor output by 50%

I have a persistent problem (from my perspective, at least). Every time I use XSLTProcessor.transformToFragment, the output is consistently halved compared to the input. For example, when I receive 200 entries in an XML file as a response from a webservi ...

Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) { using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() { if (x.state == 4 && x.responseCode == 200) notifyUser(i); } } My goal now is to e ...

Querying with Codeigniter in Ajax Data table only returns a single row

When using codeigniter to create an ajax data-table, I pass the User ID as a condition to retrieve records from a product orders table. $this->datatables->select('orders.order_user_id,orders.order_date,orders.order_id,orders.order_confirmation_ ...

Having trouble positioning a specific element at the top right of the header navbar in Laravel Bootstrap 5

Is there a way to create a top navbar with the project name and menu on the left, and user management on the right? Currently, both options are aligned to the left. Here is an example of what I have: top navbar This navbar is placed in the header, and her ...

The dynamic import() syntax is not compatible with the target environment, preventing the use of external type 'module' in a script

I am currently facing an issue with my React app. The command npm start is working as expected, but when I try to run npm run build, it keeps failing. It's crucial for me to run npm run build in order to deploy the app on a website. I have already sp ...

Create a new tab without triggering the pop-up blocker by utilizing an iframe's JavaScript event

I currently have an iframe embedded in a webpage. Once data is successfully sent to the server within the iframe, the server responds with a new URL to be opened either in a new tab or the parent window. The main issue I am encountering is that the brows ...

Insert information into a nested array using Mongoose

I'm encountering an issue with my code, even though I know it may be a duplicate. Here is the snippet causing me trouble: exports.addTechnologyPost = function(req, res){ console.log(req.params.name); var query = { name: 'test ...

Encountering a "Evaluation Failed" error while scraping YouTube data with Puppeteer and Node.js

As I attempt to scrape the YouTube headline and link from a channel using Puppeteer, I encounter an Evaluation Error presenting the following message: Error: Evaluation failed: TypeError: Cannot read properties of null (reading 'innerText') a ...

Exploring Angular modules has shed light on a certain behavior that has left me puzzled - specifically, when diving into JavaScript code that includes the

I am currently working with angularjs version 1.4.3 and I find myself puzzled by a certain segment of code in the Jasmine Spec Runner that has been generated. Upon generation, Jasmine (using ChutzPath) creates this particular piece of code: (function ...

"Enhancing Collaboration with NextJs Multi-Zones' Unified Header

Currently, I have two applications named admin-shell and delivery-management, both of which are being managed using Multi Zones in NextJs. These applications share a common header with navigation links, but I am encountering difficulties navigating betwee ...

What is the reason for not receiving a JSON object in the response from my personal node.js/express server?

-- Exploring a New Challenge -- I am currently working on creating an e-form signup for a client as part of our business marketing strategy service. The form design is complete and looks excellent. Now, I need to connect it to the existing API that our bu ...

Tips for selecting array [0] and turning it into a clickable link with JavaScript

My challenge lies in redirecting to a different URL when the user clicks on <a href="javascript:void(0)">Hotel Selection</a>. Below is my current progress. Grateful for any assistance! <div id="menu"> <ul> <li class= ...

What is the process of nesting widgets in kendoui with the PHP wrapper?

I have created a code using treeview in manual mode. div id="treview-back"> <?php $treeview = new \Kendo\UI\TreeView('treeview'); // function to create TreeViewItem with imageUrl function ImageTreeViewItem($text) { ...

When utilizing a computed property that accesses the Vuex state, the v-if directive alone may not function as expected without

Uncertain of the source of the issue, but the basic v-if functionality seems to be malfunctioning. <template> <div> <select v-model="col.code"> <option v-for="i in foo" :value="i.code" ...

Angular: Built-in solution for managing unhandled HTTP errors

I have implemented a default handler for handling http errors in my angularjs app as shown below: myapp.config([ '$httpProvider', function($httpProvider) { $httpProvider.responseInterceptors.push('errorInterceptor') }]) The errorI ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

What steps do I need to take to ensure that Phaser implements modifications made in my game.js file?

I recently completed the Phaser Tutorial and set up my project with an index.html file and a game.js file, along with downloading the phaser.min.js file. All files are located in the same folder. Although I have connected everything correctly and the outp ...