Kieran Rippy Thompson Kieran Rippy Thompson - 1 month ago 6
HTML Question

Setting a background image with a button in HTML/CSS

I want to set a background image to a webpage by clicking a

button
, mine isn't working, can anyone help?

Code-snippet:



body input {
background-color: #2c4c4c;
}
body input:active {
width: 100%;
height: 100%;
background-image: url(meme.jpg) no-repeat;
}

<html>

<head>
<link rel="stylesheet" href="styesheet.css" type="text/css">
</head>

<body>

<div id="container">
<form>
<input type="button" value="click me">
</form>
<!-- closing container div -->

</div>
</body>

</html>




Answer

You can't do that without JavaScript

Unfortunately CSS styles can only be applied to the selected elements and their children, neighbors, and siblings. Since the body is a parent of your button, setting styles on the button itself has no effect on it. You have to give your button an event handler that sets the background of the body tag. The easiest way to do it would be

<button onclick="changeBackground();">Click me</button>

Then create the function that will handle the click

<script type="text/javascript">

    function changeBackground() {
        document.body.style.background = 'url(meme.jpg) no-repeat';
    }

</script>

Of course this is just the tip of the iceberg if you've yet to use JavaScript, there's a lot of material about it on the web.