Search code examples
javascriptjqueryhtmlhref

Disable href property using jquery


I want to disable the a link from refreshing the page (i.e. going to the href link). But I want to the url to be modified, as per the href value.

Currently, I am trying this

$('.advertPP').click(function() {
    event.preventDefault();
    location.href = link.attr("href");
});

HTML Link

<a href="products?id=<?php echo $item_id; ?>" class="advertPP">Link</a>

Since both are on the same page, so I don't want the page to be refreshed but i want the url to be modified as in the href value.


Solution

  • Your code is full of(logical) errors.

    $('.advertPP').click(function(event) {
        event.preventDefault();
        location.href = this.href; //or $(this).attr("href"), is the same thing, jQuery is not needed in this case
    });
    

    Maybe you want your page to change contents without refreshing, so you need AJAX, here is an example:

    $('.advertPP').click(function(event) {
        event.preventDefault();
        $.ajax({
            url: this.href,
            success: function(data) {
                //if the loaded page is a full html page, replace the HTML with the data you requested
                $("body").html(data); //make sure your data has only body contents, either you can replace the full HTML even if it is a bad practice $("html").html(data);
            }
        });
    });