Aj96
Aj96

Reputation: 187

How to prevent a user from being redirected to a link in JavaScript?

var $ = function (id) {
    "use strict";
    return document.getElementById(id);
};

$(document).ready(function () {
    "use strict";
    $('redirect').click(function () {
        window.alert('you clicked the link');
        return false;
    }); 
});
 <a href="http://www.google.com" id="redirect">Visit Goggle</a>

I have a link in HTML and I wanting to use JavaScript and Jquery for the rest of my code. When the user clicks on the link, I want an alert to pop up with a message but I do not want the link to redirect them to that page. When I view my code in Chrome with the developer tools, I get an error message that says "Uncaught TypeError: cannot read property of 'ready' of null". Why is the ready property coming up null and how do I fix it?

var $ = function (id) {
    "use strict";
    return document.getElementById(id);
};

$(document).ready (function () {
    "use strict";
    $('redirect').click(function () {
        window.alert('you clicked the link');
        return false;
    }); 
});
 <a href="http://www.google.com" id="redirect">Visit Goggle</a>

`

Upvotes: 3

Views: 208

Answers (3)

Irene Mitchell
Irene Mitchell

Reputation: 44

var $ = function (id) {
    "use strict";
    return document.getElementById(id);
};

If you use $ as your jQuery wrapper, then the code above override that variable. Meaning it's no longer jQuery but rather that custom function that you have set. Try changing the name of the function or variable above.

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44145

Your issue is you're redefining jQuery's $ function to your own custom function. Don't do this! It completely nullifies jQuery (you'd have to use the verbose jQuery form). You can also use preventDefault to prevent the hyperlink changing your page.

$(document).ready(function () {
    "use strict";
    $('redirect').click(function(e) {
        e.preventDefault();
        window.alert('you clicked the link');
    }); 
});

Also make sure you have jQuery - place this at the top of your page:

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

Upvotes: 1

Lord Elrond
Lord Elrond

Reputation: 16062

You need to use e.preventDefault(), like this:

$(document).ready(function () {

    $('#redirect').click(function (e) {
        e.preventDefault();
        window.alert('you clicked the link');   
    }); 

});

Also, if you need to reference elements by class (with jQuery):

$('.someClass').on('click', function() {
 ...

If you want to access them by id:

$('#someId').on('click', function() {
...

Upvotes: 1

Related Questions