Jaskaran S.P
Jaskaran S.P

Reputation: 1125

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.

Upvotes: 1

Views: 1268

Answers (3)

Tafadzwa Gonera
Tafadzwa Gonera

Reputation: 352

I noticed that you are not passing event object to your function. You should pass the object like this:

$('.advertPP').click(function(event) {
                            //^^^^^ pass the event object
    event.preventDefault();
    $(this).attr("href", "http://...");
});

Upvotes: 1

Niccol&#242; Campolungo
Niccol&#242; Campolungo

Reputation: 12050

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);
        }
    });
});

Upvotes: 1

Anjith K P
Anjith K P

Reputation: 2158

Check whether document.URL and $(this).attr('href') are same then set new url and return false. If both are different them redirect to the page.

$('a').click(function() {
    var currentUrl = document.URL
    if ($(this).attr('href') == currentUrl) {
        $(this).attr('href', 'http://www.google.com');
        return false;
    }
})

Upvotes: 1

Related Questions