Search code examples
javascripthtmlcssbuttonclick

Change body background-image onclick with images from ul


I want to got a body with a defined background-image and be able to choose from a ul to the background i want to change(ex:car,dog,house...).

body {
    width:1200px;
    height:907px;
    background-image: url("fotos/cc.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

<body>          
<select id="borde" onchange="encender();" name="select1">
            <option value="0" selected="selected"></option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
          </select>
</body>

Solution

  • You didn't clearly specify what you want to do with select tag. However as I understood you want to change background image on option change. Your eventHandler is calling a function which is not created. I have called onchange event via JQuery to store background Image from selected option value in the code below.

         var body = document.getElementById('body');
         var select= document.getElementById('borde');
         $('select[name=select1]').on('change', function(){
              body.style.backgroundImage = 	String('url('+	select.children[select.selectedIndex].getAttribute('value')+')')
         })
    body {
        width:1200px;
        height:907px;
        background-image: url("http://cdn3.megarush.net/wp-content/uploads/2013/01/search-engine-friendly-urls.jpg");
        background-repeat: no-repeat;
        background-size: 100% 100%;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <body id ='body'>          
    <select id="borde" name="select1">
                <option value="http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg">default</option>
                <option value="https://res.cloudinary.com/ahrefs/image/upload/v1407314140/production-application-pending-logo-152.jpg">1</option>
                <option value="http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg">2</option>
                <option value="http://topwalls.net/wallpapers/2012/01/Nature-sea-scenery-travel-photography-image-768x1366.jpg">3</option>
                <option value="http://img.gettyimageslatam.com/public/userfiles/redesign/images/landing/home/img_entry_002.jpg">4</option>
              </select>
    </body>