Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a div a link in JavaScript?

Tags:

javascript

css

Everything I've searched for has shown about making a full div clickable, what I'm wondering is, is it possible to make a div in to a clickable link using just JavaScript and the div ID?

I have a layout of boxes and if a value in my database, I want PHP to echo some values in to JavaScript and say if this box is taken, give this div (boxID) the link that relates to it from the database. Only, there aren't going to be links on every div, as some won't exist in the database.

I suppose the alternative to this is wrapping each div in a <a> tag and an if exists statement?

like image 453
BN83 Avatar asked Feb 19 '26 14:02

BN83


2 Answers

In pure JS:

document.getElementById('your-div').addEventListener('click', function() {
    location.href = 'http://your-url.com'
}, false);

By jQuery

$('#your-div').on('click', function() {
    location.href = 'http://your-url.com'    
});
like image 149
Astralian Avatar answered Feb 21 '26 04:02

Astralian


you can easily make it so that when you click your div you go to another page, like this (using jQuery)

$('#myId').click(function () {
    window.location = 'newurl.php';
});
like image 30
Damien Black Avatar answered Feb 21 '26 03:02

Damien Black



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!