Problem with Jquery when attempting to modify or retrieve a URL

Trying to implement a script that loads the output of the variable "url" in the browser when clicking an anchor tag. The alert box displays the expected result path, but the link opens the path mentioned in the anchor tag. Seeking assistance in resolving this issue.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    $(document).ready(function(){   
        $("a").on('click', function(){
            var reqURL = window.location.href;
            var hrefVal = $(this).attr('href');
            var url;        
            if(hrefVal.indexOf("http")== -1){
                if(reqURL.indexOf("/ca-en") != -1){
                    url="http://www.mywebsite.com/site2"+hrefVal;
                }else if(reqURL.indexOf("/ca-fr")> -1){
                    url="http://www.mywebsite.com/site3"+hrefVal;
                }else{
                    url="http://www.mywebsite.com"+hrefVal;     
                }
                alert(url);
                window.open(url,"_self");
            }       
        });
    });
    </script>
</head>

<body>
    <ul>
    <li>
        <a class="category" href="/home.html">home<span class="icon plus"></span></a>
        <ul class="submenu">
            <li><a href="/home/abc.html">abc</a></li>
            <li><a href="/home/xyz.html">xyz</a></li>
            <li><a href="/home/tam.html">tam</a></li>
        </ul>
    </li>
    </ul>
</body>
</html>

Answer №1

To ensure your custom behavior logic is executed properly, it is important to first prevent the default behavior of the anchor tag. You can achieve this by implementing the following code snippet:

<script>
$(function(){   
    $("a").on('click', function(e){
        e.preventDefault();
        var reqURL = window.location.href;
        var hrefVal = $(this).attr('href');
        var url;        
        if(hrefVal.indexOf("http")== -1){
            if(reqURL.indexOf("/ca-en") != -1){
                url="http://www.mywebsite.com/site2"+hrefVal;
            }else if(reqURL.indexOf("/ca-fr")> -1){
                url="http://www.mywebsite.com/site3"+hrefVal;
            }else{
                url="http://www.mywebsite.com"+hrefVal;     
            }
            alert(url);
            window.open(url,"_self");
        }       
    });
});
</script>

Answer №2

Ensure to include the onclick function within the anchor tag to prevent it from immediately redirecting to the href path before the JavaScript window.open function is executed.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>

    function redirect(parameter){
            var reqURL = window.location.href;
            var hrefVal = parameter;
            var url;        
            if(hrefVal.indexOf("http")==-1){
                if(reqURL.indexOf("/ca-en")!=-1){
                    url="http://www.mywebsite.com/site2"+hrefVal;
                }else if(reqURL.indexOf("/ca-fr")>-1){
                    url="http://www.mywebsite.com/site3"+hrefVal;
                }else{
                    url="http://www.mywebsite.com"+hrefVal;     
                }
                alert(url);
                window.open(url,"_self");

            }
    }

    </script>
</head>

<body>
    <ul>
    <li>
        <a class="category" href="/home.html">home<span class="icon plus"></span></a>
        <ul class="submenu">
            <li><a href="#" onclick="redirect('/home/abc.html')">abc</a></li>
            <li><a href="#" onclick="redirect('/home/xyz.html')">xyz</a></li>
            <li><a href="#" onclick="redirect('/home/tam.html')">tam</a></li>
        </ul>
    </li>
    </ul>
</body>
</html>

Answer №3

- <li><a href="/home/xyz.html">xyz</a></li>

+ <li><a href="javascript:void(0);" data-url="/home/xyz.html">xyz</a></li>


- var linkVal = $(this).attr('href');

+ var linkVal = $(this).data('url');

Extremely straightforward..

Answer №4

The main concern arises when utilizing the <a> tag, as it traditionally directs to the specified value in the href. Therefore, prior to running your script, it is essential to prevent the default behavior of the <a> tag.

Integrate event.preventDefault() within your onclick script. This will effectively block the automatic redirection of your <a> tag.

Check out this informative example for further understanding.

Trust this explanation proves beneficial.

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

Replace the <button> tag with an <input> tag that triggers an onclick event

I am struggling to swap one element for another using an "onclick()" function. I can create new elements, but that doesn't solve my problem. Imagine I have a element that I want to replace with a different element on the same spot. I am familiar w ...

Using a web browser control to choose a radio button and then submit the form

Currently, I am attempting to use my WebBrowser control in order to select a radio button and also click on a submit button that doesn't have any id or name attached. Below is the snippet of HTML code from the webpage: <form method="post> & ...

Is it possible to generate a coordinate grid comprised of clickable div elements with HTML, CSS, and Javascript - with the option to utilize JQuery if necessary?

Here is a link to the code on JFiddle: http://jsfiddle.net/4v2n7wk9/1/ <html> <head> <title>Example of Grid Buttons</title> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui ...

execute a function when an image is clicked using jQuery

How can I create an onclick event for the variable imageCatuaba? function setCatuaba(map) { var imageCatuaba = { url: 'images/catuskov.1.png', origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(0, 32) }; I'm ...

Does a Function Component become an object instance of itself when rendered with a tag?

Suppose I declare a constant variable num = 1 inside a function component. Would it be possible for me to reference this variable in the return statement as this.num? Is it permissible for function components to contain static variables of that nature? ...

In HTML, employing the float:left property and using relative positioning are essential

I've encountered a strange issue when using a div block with float:left and another with relative position. The second block is behaving unexpectedly, as the text is extending beyond the box and its background color. Can anyone help me understand what ...

Choose a specific portion of text following an element in HTML using CSS

I would like to style the text following the span tag using CSS without affecting the span tag itself. Specifically, I want to apply styling only to the text that reads "Text to be selected", leaving the span tag unaffected. The style I desire i ...

How do I initiate a TypeScript Node server via the terminal?

I'm trying to start this Node app written in TypeScript, you can find the code here. Although I have TypeScript installed, I'm unsure how to begin running the Node server. Can anyone help me with this? ...

In Vue.js, the splice method consistently removes the final item from an array

I've been stuck on this seemingly simple problem for hours. I developed an app that allows users to add or remove files for upload. However, whenever I click the delete button, it always removes the last item. I tried adding :key="key", bu ...

Ways to ensure the bootstrap table header width aligns perfectly with the body width

I am having an issue with my bootstrap table where the header width is smaller than the body width because I set the table width to auto. How can I align the header and body widths? Here is a link to a plunker showcasing the problem. https://plnkr.co/edit ...

Code for handling ASP.NET button click events on both the client and server side

I need to add a confirmation popup to my asp:button named "Delete". The popup should have options "Yes" and "No". If the user clicks on "Yes", I want to delete a record from a SQL database. If the user clicks on "No", nothing should happen. <asp:Button ...

Automatically saving form data on page unload is not finishing before the page is refreshed

Hey there! I've got a page that has a dynamic number of textareas. So, when the unload event is triggered, I do a little check to see which textareas have been updated. Then, I send off an AJAX post request to an MVC controller, which does its thing a ...

What is the best way to conceal a route within the Angular 2 router?

Currently, my setup involves using angular 2 with router 3.0.0-rc.1. In the tutorial I am following, there is a specific template that is used for navigation: ` <nav> <a routerLink="/crisis-center" routerLinkActive="active" [routerLink ...

"Keep an eye on the value of elements within Angular framework

I am trying to develop a directive that can be used in the following way: <div before-today="old">{{exampleDate}}</div> The purpose of my directive is to check if the date within the div is before "today" and if it is, apply the CSS class "ol ...

Eliminating `<style>` tags within the `<head>` section

Our software system is generating unnecessary <style> tags within the <head> section. These tags are not required and need to be removed. I attempted to remove them using the following approach, but it seems that my logic may have some flaws. ...

What is the optimal strategy for incorporating both useLazyQuery and useQuery within the Apollo-client based on specific conditions?

In the navigation menu, I have options for "foods" and "cakes." The Foods page displays a list of all food items url: /foods When the user clicks on cakes, they are redirected to /foods?food=cakes, which is essentially the same page as the foods above. ...

Django is refusing to display my CSS and JavaScript files - static files

Within my code in settings.py, I define the static URL like so: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' The location of my static files and folders is at /home/myLinuxUsername/myApp/static/interactive-preview-depe ...

Why does one part of my Django website appear less appealing on a smartphone compared to the rest?

Looking for some advice for my django website. I recently deployed it on heroku and it seems to be working well, except for the "final view" on smartphones. Everything looks good on PC, but on mobile devices, there is a slight horizontal and vertical scrol ...

Tutorial on implementing an AJAX save button featuring a loading GIF in CKEditor version 4.2.1. [Interactive Plugin Demo Included]

Sharing this post as a helpful guide for anyone looking to display a save icon in ckeditor for normal and inline-editing mode. After struggling to find a working save plugin for ckeditor 4.2.1, I took matters into my own hands and created my own. In my res ...

Following the upload process, my webpage is mistakenly referencing the wrong directories

After completing a mock site project, I encountered an issue where the styling was perfect locally but did not show up once uploaded to my server and Github pages. Looking into the console, I found this error message: Failed to load resource: the server ...