3

I want to nest a button that performs an Ajax action that is between <a> tags. enter image description here

The whole container should act as a link to a separate webpage while the "favorite" button will perform an unrelated Ajax action. Unfortunately, this is not able to be done because <button> cannot be nested inside an <a> tag.

Is there a simple workaround to achieve to this effect?

Current code:

<a class="button7" onmouseover="displayFavorite('000')" onmouseout="hideFavorite('000')" href="http://www.example.com">
    Math 141
    <button id='000' class="button8" onclick="favorite('000')">Favorite</button>
    <ul>
        <li><strong>Description</strong> Calculus 1 and Calulus 2</li>
        <li><strong>Instructor</strong> Boon Ong</li>
        <li><strong>Documents</strong> 17</li>
    </ul>
</a>

EDIT: Please note, the AJAX was just additional information, its not related to the question.

TylerH
  • 20,799
  • 66
  • 75
  • 101
user3677286
  • 125
  • 2
  • 9

2 Answers2

5

Something like this:

<div class="container">
    <a class="button7" href="http://google.co.uk" onmouseover="displayFavorite('000')" onmouseout="hideFavorite('000')">
        Math 141
    
        <ul>
            <li><strong>Description</strong> Calculus 1 and Calulus 2</li>
            <li><strong>Instructor</strong> Boon Ong</li>
            <li><strong>Documents</strong> 17</li>
        </ul>
    </a>
    <button id='000' class="button8" onclick="favorite('000')">Favorite</button>
</div>

CSS:

.container {
    position:relative;
    width:400px;
}
.button7 {
    width:100%;
    height:auto;
    display:block;
    background:red;
}
.button8 {
    position:absolute;
    top:5px;
    right:5px;
}

Positioning an element absolutely in a parent container with position:relative; enables you to use the css properties top, left, right, and bottom relative to the container that encloses it.

Setting the <a> (with class .button7) to display:block; means that the hyperlink will act as a block level element and take up the entire "block" (i.e. space afforded to it by its parent)

http://jsfiddle.net/t29m4/

TylerH
  • 20,799
  • 66
  • 75
  • 101
adaam
  • 3,700
  • 7
  • 27
  • 51
0

Another option, which has the advantage of only requiring you to make a one line change, is to prevent the click event from propagating up to the link. You can do this by calling event.preventDefault() when the button is clicked.

<button id='000' class="button8" onclick="(e)=>{favorite('000'); e.preventDefault();}">Favorite</button>

Not sure if this syntax is quite right or if this approach follows best practices, but there does seem to be good browser support for preventDefault

Looks like this approach was recommended on SO before

College Student
  • 1,719
  • 16
  • 15