0

I wanted to make this statement using jQuery but cant quite get it to work. In this statement I am clicking on an image in my html and changing it to a new image (img/HeaderImg2.jpg) Please help.

  var imageButton = document.getElementById('headerImg');
  imageButton.addEventListener('click', function(e)
  {
   console.log(e);
   imageButton.src ='img/HeaderImg2.jpg';
  } ,false);
3
  • Why do you want to switch to jQuery if it's already working with vanilla JavaScript? Don't fix it if it ain't broke. Commented Jan 27, 2014 at 3:07
  • @ElliotBonneville Perhaps he wants to know more about jQuery. Commented Jan 27, 2014 at 3:08
  • I understand that if the javascript works then keep it but I am trying to learn jQuery and how it functions. Commented Jan 27, 2014 at 3:33

1 Answer 1

3

Try this:

$('#headerImg').on('click',function(e) {
    console.log(e);
    $(this).attr('src','img/HeaderImg2.jpg');
});

Btw, it's better to use vanilla javascript other than using jQuery if you're able to do so.

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

3 Comments

Thank you that was very helpful. If I wanted to make my header change as well when I click the same image how would I do that? right now I am using childnodes. var pageTitle = document.getElementById('header'); imageButton.addEventListener('click', function(e) { console.log(header.childNodes); header.childNodes[1].innerHTML = "Hello" } ,false);
You can try to use: $('#header').find(':eq(1)').html('Hello');
it's better to use vanilla javascript other than using jQuery if you're able to do so I'd say that depends, if I already had jQuery library included then I would use it over vanilla JS, but wouldn't include it just for the sake of it. Just be consistent across a project too.

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.