Search code examples
htmlbuttonhref

Button that contains an Href with event


I have an href on a TEXT that is performing an action . (the action is changing the div i am using with another div). I would like to change the TEXT as a BUTTON but i know i cannot innest a "button tag" into the "a tag".

    <a href="EXTERNALPAGE.html"  onmousedown="loadextPage(event) ">  BACKBUTTON </a> 

    <button id="back_button"> BACKBUTTON   </button> 

In addition this is the code of the event:

      function loadextPage(event) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('pop_up_frame').innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", event.target.href, true);
        xmlhttp.send();

}

solved with

        <div id="back_button" onclick="return false" onmousedown="loadextPage(event)"                 style="cursor:pointer">
    <button>
        <a href="secondpopup.html">   Go Back </a>
    </button>
        </div>

and

<script>

    function loadextPage(event) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('pop_up_frame').innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", event.target.href, true);
        xmlhttp.send();
    }




</script>

Solution

  • When I saw your function loadextPage(event) I know why you want an anchor tag, because the function is getting the href of the clicked element to load the external page. So you can use a button with data attribute like this

    <button id="back_button" data-href="EXTERNALPAGE.html" onmousedown="loadextPage(event)"> BACKBUTTON   </button>
    

    And you need to change you function to this

    function loadextPage(event) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('pop_up_frame').innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", event.target.dataset.href, true);
        xmlhttp.send();
       }
    

    So from this

    xmlhttp.open("GET", event.target.href, true);
    

    To

    xmlhttp.open("GET", event.target.dataset.href, true);
    

    Example http://jsfiddle.net/2vka9ubj/