Change the CSS menu item to directly load the website instead of using javascript to replace a placeholder

I have a CSS navigation menu, but I'm facing an issue. When I click on a link in the menu, like Google for example, it only changes the name of the placeholder and doesn't actually load the page. Any suggestions on how to fix this?

Thank you for your assistance!

Here is a fiddle example where you can try to load Google from the menu: http://jsfiddle.net/n877s/3/


function DropDown(el) {
    this.dd = el;
    this.placeholder = this.dd.children('span');
    this.opts = this.dd.find('ul.dropdown > li');
    this.val = '';
    this.index = -1;
    this.initEvents();
}
DropDown.prototype = {
    initEvents : function() {
        var obj = this;

        obj.dd.on('click', function(event){
            $(this).toggleClass('active');
            return false;
        });

        obj.opts.on('click',function(){
            var opt = $(this);
            obj.val = opt.text();
            obj.index = opt.index();
            obj.placeholder.text(obj.val);
        });
    },
    getValue : function() {
        return this.val;
    },
    getIndex : function() {
        return this.index;
    }
}

$(function() {

    var dd = new DropDown( $('#dd') );

    $(document).click(function() {
        // close all dropdowns
        $('.wrapper-dropdown-3').removeClass('active');
    });

});

HTML

<div class="wrapper-demo">
<div id="dd" class="wrapper-dropdown-3" tabindex="1">
    <span>Transport</span>
        <ul class="dropdown">
        <li><a href="#">Classic mail</a></li>
        <li><a href="#">UPS Delivery</a></li>
        <li><a href="http://www.google.com">Google</a></li>
        </ul>
</div>

Answer №1

To alter the standard link behavior, including descendant links, you can implement the following code:

        obj.dd.on('click', function(event){
            $(this).toggleClass('active');
            return false;
        });

To prevent clicks on menu items from reaching the above handler, include this additional code:

        obj.dd.find('a').on('click',function(event){
            event.stopPropagation();
        });

You can see a functional example in this JSFiddle demo.

Please note that due to the SAMEORIGIN policy, google.com will not load in the jsfiddle iframe; check the console for the outcome.

Answer №2

The <a> tags are nested within the <div id="dd">, and the div contains a script that triggers on click events to prevent default actions using false. When a click event occurs on the a tag, it propagates up to the div element which halts it from executing.

To resolve this issue, you can insert the following code:

if ($(event.target).is("a[href!=#]"))
    return true;

right before the return false; statement

Answer №3

The first method involves removing return false; from the click event of obj.dd, and replacing it with event.stopPropagation(); at the beginning. This will allow the link href attributes to load the page as intended. Here's how:

obj.dd.on('click', function(event){
    event.stopPropagation();

    $(this).toggleClass('active');
});

An alternative method is to try this approach:

obj.opts.on('click',function(e){
    e.preventDefault();

    var opt = $(this);
    obj.val = opt.text();
    obj.index = opt.index();
    obj.placeholder.text(obj.val);

    window.location.href = opt.attr('href');
});

In your HTML code, simply add links similar to the google link you currently have.

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

Using CSS to resize an element with both dimensions while maintaining its

Is it feasible to preserve a 1:1 aspect ratio on a div element using the CSS resize property? This particular illustration lacks an aspect ratio. Do you have any recommendations? ...

Removing characters from a string with regular expressions

I need to eliminate instances of << any words #_ from the given text. stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ "; The d ...

FingerprintJS is experiencing an issue with the navigator object not being defined, resulting in

I am currently working on extracting browser fingerprint using fingerprintjs2, an npm package in Javascript. However, I encountered the following error: ReferenceError: navigator is not defined Error Logs: https://i.sstatic.net/lWL9Y.png Code Snippet: ...

Could anyone please provide advice on how to resolve the issue I encountered when trying to make Post and get Http method calls using protractor?

I am currently facing an issue while trying to make a GET API request using protractor. The challenge lies in using the bearer token generated from a previous POST response in the headers of the GET request. Although I have successfully executed the POST r ...

Excessive Width Issue Caused by Bootstrap 4 Navbar Items

Having trouble with my Bootstrap 4 Navbar menu implementation. When I add more items, they overflow the container instead of floating correctly. Any CSS suggestions to temporarily fix this issue? <!DOCTYPE html> <html lang="en"> <head> ...

Steps to link two mat-autocomplete components based on the input change of one another

After reviewing the content on the official document at https://material.angular.io/components/autocomplete/examples I have implemented Autocomplete in my code based on the example provided. However, I need additional functionality beyond simple integrati ...

React Native Function fails to return a value

Within my React Native app, there's a page called RepsPage that displays a scroll view using an array of IDs. I'm passing this array to a function named renderRep, attempting to create a view for each item in the array. However, the return statem ...

Utilize vue.js to save the components of an object

data() { return: { user: {}, userName: "", userAge: "" } }, methods: { saveUserName: function() { this.userName = this.newUserName; this.$refs.userNameModal.hideModal(); this.$ ...

The property 'matMenuTrigger' cannot be attached to 'a' because it is not recognized

Trying to implement matMenuTrigger but encountering an error saying "Can't bind to 'matMenuTrigger' since it isn't a known property of 'a'". Any assistance would be greatly appreciated. ...

Ways to dynamically update CSS properties (such as changing the color scheme throughout the entire application)

I have a question... If you're interested in conditional styling, the best approach is to utilize either ng-class or ng-style. However... For instance, let's say I'm an admin and I would like to customize the color of my application using ...

Tips on invoking a factory method from a different service method in AngularJS

I have a factory method that goes like this.. (function (angular) { "use strict"; angular .module('app') .factory('UserService', ['$rootScope', '$q', function ($rootScope, $q) { ...

Arranging Divs into Two Columns in CSS - A Simple Guide

I'm trying to display a variable number of divs across two lines, like this: [1] [3] [5] [7] [2] [4] [6] ... I've explored using the column-count property in CSS, but it doesn't quite fit my needs since it requires a fixed number of ...

Angular and Three JS collaboration leads to misplacement of canvas rendering

Currently in the process of developing code for a website, I am attempting to integrate Three JS with Angular. After conducting some research, I have found that this combination is feasible and I have successfully merged these two libraries. However, I am ...

The controller method in MVC is not receiving the expected data

Recently delving into MVC, I find myself faced with a challenge: editing a row and sending the modified data to a controller method using jQuery and AJAX. Upon clicking the edit button, the designated row transforms into textboxes and reveals a "save" `Act ...

Tips for styling an inline list using CSS before revealing it with jQuery's .show method:

In my project, I want to display a row of 'cells' which are simply images of black or white squares based on their ID. The issue I am facing is that when the button is clicked, the row list is shown without the CSS applied, and then after a brief ...

Styling the tab view in PrimeFaces

I am currently working with the tab view feature in primefaces and I have encountered a couple of issues. 1) When using Internet Explorer, the tabs are displayed vertically instead of horizontally. However, it works fine in Firefox. FireFox : Internet E ...

Tips on choosing and showcasing information from jQuery date and time picker

I am struggling to show the selected data from a jQuery date and time picker and save it to a database using PHP with MySQL. I am not sure how to retrieve the information. Here is the jQuery code for the date and time picker along with a suggested jQuery f ...

Creating an IF statement within a jQuery / Ajax request when using PHP

Does anyone know how to implement an IF statement inside jQuery? I am currently working with two rows of data in a database that have different statuses. https://i.sstatic.net/N27y1.png My main file for displaying the data is index.php. Here is a snipp ...

Customizing the date-select widths: A step-by-step guide

I've been struggling with adjusting the width of different instances of this line: <%= f.date_select :deadline, :order => [:month, :day, :year], class: 'date-pick', id: 'goal' %> Despite creating unique ids for select, d ...

Tips for displaying a loading spinner each time the material table is loading

Hey there, I'm currently working on an Angular project where I need to display a table using Material Table. To indicate that the table is loading, I've defined a variable called isLoading. Here's how it works: In my TypeScript file: @Com ...