0

This is the JavaScript code I wrote :

var goToSecondPage= document.querySelector('.mobile');

goToSecondPage.addEventListener("click", function() {

document.location.href='productDetails.html';
 })

I'm trying to use an image in an existed class on an index html page (called mobile) and make it as a clickable link image to another html file called productDetails.html

3
  • Does this answer your question? How do I add a .click() event to an image? Commented Mar 13, 2022 at 10:57
  • 1
    Is there a reason you can't wrap the <img /> in an <a>? (i.e. Do you control the HTML or not? If you do, then just add a <a> in the HTML and skip scripting entirely - that way users using keyboard-navigation can navigate, as well as middle-clicking for opening in a new tab, as well as supporting users with JS disabled, etc. Commented Mar 13, 2022 at 10:57
  • Can you add the HTML to your question as a minimal reproducible example, please? Commented Mar 13, 2022 at 10:57

1 Answer 1

1

It depends where your productDetails.html file is located. If it's in the root directory try

var goToSecondPage = document.querySelector('.mobile');

goToSecondPage.addEventListener("click", function() {
    document.location.pathname = '/productDetails.html';
});

This will only change your path, not the entire url.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.