Search code examples
javascripthtmlcsstoggletogglebutton

Javascript toggling image and div


I am trying to toggle an image and toggle a Div' visibility at the same time, this is what I have so far. When I click on the image to activate the Toggle it is submitting the form, which isn't ideal...

<div class="field">

        <script>
  function toggle(){
if(el.className!="off")
{
    el.src='off.png';
    el.className="off";
    var div1 = document.getElementById('1')
    div1.style.display = 'block'
}
else if(el.className=="off")
{
    el.src='on.png';
    el.className="on";
    var div1 = document.getElementById('1')
    div1.style.display = 'none'
}

return false;
}
        </script>

      <label for="Recurring">Recurring:</label> <input style="width:60px;" type="image" src="on.png" class="on" onclick="toggle();"/></div>

      <div style='display:none;' id="1" class="field"><label for="frequency">Please select the frequency:</label><select id="frequency" name="frequency">

        <option value>Please Select</option>
        <option value="10">10</option>

        </select>
        </div>

Solution

  • I would change your code a bit, to add a event listener rather than inject the javascript into your markup (which is the preferred method). You can try this code:

     window.onload = function() {
    
            var input = document.getElementById('input');
    
            input.addEventListener('click', toggle);
    
     }
    

    The input will need id='input and the toggle function will need to be slightly modified:

    function toggle(e){
        e.preventDefault();
    
        var el = e.toElement
    
        //rest of code
    
    }
    

    The e.preventDefault() is what will keep the page from refreshing.