2
<!DOCTYPE html>
<html>
    <style></style>
<script src="main.js">
    function myFunction() {
        document.body.style.background = "url('images/img_tree.png')"
    }
</script>

<body>
    <button onclick="myFunction()">Set background</button>
</body></html>

Why won't this work? I am using the brackets IDE currently.

0

4 Answers 4

0

You need to remove the src="main.js" from your script tag

Does this fix it ?

<!DOCTYPE html>
<html>
    <style></style>
  <script>
      function myFunction() {
          document.body.style.background = "url('https://fsb.zobj.net/crop.php?r=e9wUbuA4gtFtr46UA2PE5GMcriRP4IPSzPTWOBs82VJEK_zIJcyRW5kh6JE_GrxfEmFki6gil-dD-LL5eMpMNcj5Sjw4u4Y6MwkMhR-1WlgJ50l6FRXVLRylR_2lbwvcMeLEOIUkEzNPODPaAqMfI4ClDs3vu9s3Z2s8bF55uCt0KPXzxye5ueQyfDyFFgfks2aGkOwr7pURMvK_')"
      }
  </script>

  <body>
      <button onclick="myFunction()">Set background</button>
  </body>
</html>

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

Comments

0

Delete src="main.js" on script tag

if you want to use main.js file. you have to add extra script tag

like this

<!DOCTYPE html>
<html>
    <style></style>
<script src="main.js"></script>
<script>
    function myFunction() {
        document.body.style.background = "url('images/img_tree.png')"
    }
</script>

<body>
    <button onclick="myFunction()">Set background</button>
</body></html>

Or you can add myFunction on your main.js file

Comments

0

The problem is you set src="main.js", in this case all script inside script tag will be not execute, it only execute javascript in main.js file.

<!DOCTYPE html>
<html>
    <style></style>
<script>
    function myFunction() {
        document.body.style.background = "url('https://geology.com/world/world-map-360.gif')"
    }
</script>

<body>
    <button onclick="myFunction()">Set background</button>
</body></html>

Comments

-1

Use the following code snippet for the add background image.

// Sets the background image
const setBackground = (image) => {
  document.body.style.background = "url('"+IMAGE_URLS.[image]+"')";
};

3 Comments

“While this code may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. ” :)
This won't work. You've changed the function name (for no apparent reason) so the attempt to call it will fail. You've changed the value from being a hard coded string (which was fine) to one generated by mashing three different strings together … and only of them depends on a variable which isn't defined.
Just try this. This is working!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.