This hyperlink is not redirecting to an external website

I recently downloaded a one pager template that has a unique design. All the hyperlinks within the template are set to link to specific sections on the page and use a data-link="" parameter.

However, I encountered an issue when trying to link one of the menu items to an external URL with target _blank. Instead of directing me to the external page, it was looking for a section on the same page based on the URL I provided (e.g., www.example.com/).

The links in the template have href values like this:

href="/home/" or href="/menu/"

<ul id="w1" class="navbar-nav nav">
    <li><a id="navhome" class="" href="/home" title="Home" data-link="home">Home</a></li>
    <li><a id="navmenu" class="" href="/menu" title="Menu" data-link="menu">Menu</a></li>

Even when attempting without target _blank, the external linking did not work:

<li><a id="navorder" href="http://order.company.com" target="_blank">Order Now</a></li>

I am curious to know what technology is being used here and how I can successfully link a new menu item to an external page.

UPDATE:

I managed to locate the code responsible for handling the href:

$(".menu ul li a").not('.social-link').click(function(e) {
    e.preventDefault();
    $(".menu ul li a").removeClass("active");

    tabTarget = $(this).data('link');
    animateByMenu = true;

    var hash = '#' + tabTarget;
    var url = $(this).prop('href');
    var menuItem = $(this).data('link');
    $(".menu li a[data-link=" + menuItem + "]").addClass("active");

    if (url) {
        var top = $(hash).offset().top - 60;
        $('html, body').animate({
            scrollTop: top
        }, 600, function(){

        });
        history.pushState('', '', url);
        $('.navbar-toggle:visible').click();
    }

    return false;

});

Upon clicking the link, I am receiving the following error in the console:

main.js:109 Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLAnchorElement.<anonymous> (main.js:109)
at HTMLAnchorElement.dispatch (jquery.min.js:3)
at HTMLAnchorElement.r.handle (jquery.min.js:3)

Answer №1

To capture all "a" clicks and prevent their default behavior, it's important to implement a piece of code for that purpose. Try removing the data attribute and using a simple href instead. This approach should be effective.

If following strict coding guidelines poses an issue, consider implementing a workaround such as using a div element and attaching a click handler to it.

Answer №2

If you are unsure about the type of template you are using, you can try implementing the following code snippet:

<ul id="w1" class="navbar-nav nav">
    <li><a id="navhome" class="" href="/home" title="Home" data-link="home">Home</a></li>
    <li><a onclick="window.open('http://www.google.com', '_blank')">Menu</a></li>
</ul>

By using this code, you will be redirected to another page in a new tab. Give it a try and see if it meets your needs as a simple workaround solution.

Answer №3

Alright, let's take a look at this line:

$(".menu ul li a").not('.social-link').click(function(e) {

If you want to exclude another class from the selection, you can add a new class (.external-link) and adjust the code like this:

$(".menu ul li a").not('.social-link').not('.external-link').click(function(e) {

Alternatively, you can make your code smarter by detecting external links based on their href attribute (currently only checking for http, not https):

$(".menu ul li a").not('.social-link').click(function(e) {
    if (e.target.href.indexOf('http://') !== 0) {
        e.preventDefault();
    }
...

Answer №4

One of the key observations is that JavaScript intercepts all links (potentially with a more specific selector), halts their default action (i.e., following the link), and smoothly scrolls to the designated section. Here's an example using jQuery:

$("a").each(function(i, el) {
  const $el = $(el);
  $el.click(function(e) {
    const href = $el.attr("href");
    // Locate the element with the matching ID
    // Scroll to said element
    $("html, body").scrollTop($("#" + href).offset().top);
    // Prevent default action to avoid redirecting
    e.preventDefault();
  });
});

Regarding your recent modification. Personally, I find the provided JS code lacking in quality. However, focusing on the issue: If you wish some links to open in a new tab, assign them a distinct class such as external.

<li><a id="navorder" href="http://order.company.com" target="_blank" class="external">Order Now</a></li>

Update the first line of the jQuery snippet as follows, ensuring that the click event handler excludes elements with the class .external:

$(".menu ul li a").not('.social-link, .external').click(function(e) {

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

The point in the vector data is incorrectly positioned on the map in OpenLayers

I am looking to display a world map using the default OpenLayers WMS, along with a single point on it that will have interactive events like onhover. Below is my code snippet: var options = { projection: ...

I tried utilizing the wrapper feature, but unfortunately, the modal did

import React, { PropTypes } from 'react'; import Dialog from 'material-ui/Dialog'; export default class CustomModal extends React.Component { constructor(props){ super(props) } handlePrimaryButton = () => { this.prop ...

Display everything when an option is clicked

I have a filter that is working perfectly. When I select a specific category, it filters out only rows with that category. However, I am stuck on how to display all rows again after clicking on the first option. My objective is to show all rows when "Categ ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

What is the best way to update a specific section of my website by modifying the URL while keeping the menus fixed and the site functioning smoothly?

I am in desperate need of assistance as I search for a solution. Currently, I am working on a project involving music within a web browser or application. My goal is to utilize HTML, PHP, JS, and CSS to create this project. If I start with a website, I p ...

I'm receiving the error message "Fatal error: Call to a member function query() on a non-object," what could be causing this issue?

Need help with fixing an error on my private server realmeye. The error message I'm receiving is: Fatal error: Call to a member function query() on a non-object in /home/noxus/public_html/realmeye/index.php on line 112 =========================== ...

Facing issues with integrating Mixpanel with NestJS as the tracking function cannot be located

While utilizing mixpanel node (yarn add mixpanel) in conjunction with NestJS, I have encountered an issue where only the init function is recognized. Despite calling this function, I am unable to invoke the track function and receive the error message: Ty ...

Most efficient method to upload numerous images without any lag

I have a website where images are loaded only when they are slightly below the viewport. This method allows the site to load initially without images and then determine which ones need to be loaded based on the user's viewpoint. When a user scrolls ...

Trigger Element Upon Click

Forgive me in advance for the lack of quality in this question, but I'll proceed anyway: All I want is for an element to slide open when clicked with a mouse! That's all! More specifically, I am looking for a single menu item that, upon clickin ...

Issue with CORS when starting SAM local API

I have encountered a CORS issue while using AWS CDK (Typescript) and running SAM local start-api to launch an API connected to lambda resolvers. The problem arises when attempting to access the API from a web browser. Below is the code snippet causing the ...

In AngularJS, modifying the value of a copied variable will result in the corresponding change in the value of the main

I'm facing a peculiar issue. I have an array of objects and I used angular.forEach to update the price key value of each object. However, when I make changes in each object, it also affects the main array object. Take a look at the code snippet below ...

Establish a single route for executing two different statements in MSSQL: one for updating and the other for inserting data into the MS-SQL

I have a Node application where I currently insert data into one table, but now I also need to insert it into another table. The issue is that I am unsure how to execute a second promise for this task. var query = "first SQL query..."; var query2 = "new ...

Spinning html/css content using JavaScript

Greetings! I am currently working on a demo site using just HTML, CSS, and JavaScript. Typically, I would use Ruby and render partials to handle this issue, but I wanted to challenge myself with JavaScript practice. So far, I have created a code block that ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

Nuxt.js - Struggling to Remove Event Listener

I am currently utilizing nuxt.js and have implemented a scroller that scrolls and stops at a specific point on my page. However, when I navigate to the next page, the method is still searching for the element with $ref=nav which no longer exists, resultin ...

Tips for maintaining the height of the outer div consistent with that of the inner div

I am encountering an issue with an inner div that is used for overlay and set to a min-height property. Despite changes in the overlay's height, the height of the outer div remains unaffected. #outer { width: 70px; height: 70px; background-co ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...

Retrieve the value of the key in my AngularJS JSON object

Describing my object object1 ={ name: xxx, Id: 212 } I want to transform it into: { 212:xxx } Is there anyone who can guide me on how to achieve this? for(var key in object1) { if(object1.hasOwnProperty(key)) { console.log( eac ...

Mocking Ext.Ajax.request in ExtJS 4.2.1 is a process of em

When it comes to frontend unit testing using Jasmine, one of the challenges I faced was mocking all the requests in my application. Luckily, I have already tackled a method to mock all my proxies successfully: proxy: appname.classes.proxy.ProxyNegotiator ...

Is there a way to manage the iteration of $scope.$watch?

I'm currently facing an issue with controlling the $scope.$watch function in my code. It seems to be causing an infinite loop during iteration. $scope.$watch('dashboards', function(newVal, oldVal) { if (newVal !== oldVal) { ...