0

I have a style specified in the head of my document. I specify the background image on a division but later on a need to change it if the user clicks on a link but everything I've tried to do refuses to work.

<style type="text/css">
            /*Some CSS*/
            .large {
                background: url('/images/artwork1.jpg') no-repeat;
}
</style.

<div class="large"></div>
<img id="main_image" alt="Image"/>
<img onclick="javascript:document.getElementById('main_image').sr‌​c='/images/artwork2.‌​jpg'; $('.large').css({'background-image':'url(/images/artwork2.jp‌​g)';" alt="Change Image"/>

I tried taking the background image out of the style but clicking on a link didn't change it. I've tried JavaScript and jQuery.

4
  • Please post your html as well :) Commented Sep 26, 2016 at 12:41
  • 2
    "but everything I've tried to do refuses to work" – We do not see anything in provided question :( Commented Sep 26, 2016 at 12:41
  • Sticking the label javascript: at the front of your onclick function is pointless. There is no loop to label. It does not declare that you are writing code in JavaScript. Commented Sep 26, 2016 at 13:02
  • <img onclick — Images are not designed to be interactive elements. Using one as a button introduces a number of accessibility issues. Use a button instead. <button type="button" onclick="..."><img ...></button>. (and don't neglect the alt attribute) Commented Sep 26, 2016 at 13:04

2 Answers 2

2
large

This is a type selector, it matches <large> elements.

A class selector begins with a .

$('.large').css({'background-image':'url(/images/artwork2.jpg)';
Sign up to request clarification or add additional context in comments.

6 Comments

Can I mix JavaScript and jQuery into the same onclick?
Eh? jQuery is a JavaScript library. i.e. it is nothing more than "JavaScript functions that other people wrote".
This the whole onclick statement. <img onclick="javascript:document.getElementById('main_image').src='/images/artwork2.jpg'; $('.large').css({'background-image':'url(/images/artwork2.jpg)';" The first bit used to work by now none of it works.
Since there is no main_image element, you try to access the src property of null, throw an exception and the script stops.
I had used the main_image element but I didn't include that in the code I posted. I was able to change it until I added the jQuery.
|
0

Add below code under click event

var element = document.querySelector(".large");

element.style.background = "url('/images/artwork1.jpg') no-repeat;
}";

1 Comment

I couldn't get it to work, I think it may have had something to do with all the nested quotes.

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.