Typhomism
Typhomism

Reputation: 284

element moves after click event

I have a custom dropdown that works fine, except when i click to toggle the starting element moves. Anyone have any ideas? I have tried changing code around with width position etc.

html:

    <div class="element" style="position: absolute; right: 200px; top:50px; color: white; cursor: pointer;">
        <span class="my-dropdown" href="#" id="user-name">
            john doe <span style="font-size:smaller;">&#9660;</span>
        </span>
        <ul class="my-dropdown-menu" data-for="user-name">
            <li><a href="#">Logout</a></li>
            <li><a href="#">Change Password</a></li>
            <li><a href="#">Profile</a></li>
        </ul>
    </div>

css:

.my-dropdown-menu a, .link {
  color: black;
}

.my-dropdown-menu a:visited, .visited {
   color: black;
}

.my-dropdown-menu a:active, .active {
   color: black;
}

.my-dropdown {
    color: white;
    font-size: larger;
    position: relative;
    width: 300px;
}

.my-dropdown-menu {
    display: none;
    color: black;
    font-size: large;
    text-align: left;
    padding-left: 20px;
    padding-bottom: 5px;
    padding-top: 5px;
    position: relative;
    left: -30px;
    z-index: 50;
    background-color: white;
    width: 200px;
    border-radius: 5px;
}

.my-dropdown-menu li{
    margin-top: 20px;
    margin-bottom: 20px;
}

js:

$('.my-dropdown').on("click", function () {
    var id = $(this).prop('id');
    console.log(id);
    var dropDown = $("ul[data-for='" + id + "']");
    dropDown.toggle();
});

i also put together a jsbin

Upvotes: 1

Views: 2321

Answers (2)

Trevan Hetzel
Trevan Hetzel

Reputation: 1369

.my-dropdown {
    display: block;
}

The .my-dropdown element is a span, which is not a block level element. Therefore, it doesn't take up the space that a block level element does so it moves around depending on where the next block level element is (the ul in this case, since it was hidden and then shown).

Upvotes: 1

balzafin
balzafin

Reputation: 1426

span is an inline element. Use div in .my-dropdown instead.

http://jsfiddle.net/jhut61ro/4/

EDIT:

You also have a href attribute in that element. You should remove that.

Upvotes: 2

Related Questions