Simran Nagdeo
Simran Nagdeo

Reputation: 29

How to move the element in div to first position after clicking to it

var position = $("#navigationAccount").position();
document.getElementById('navigationMobile').scrollLeft += position.left;

Upvotes: 0

Views: 994

Answers (2)

red
red

Reputation: 1619

position does not fit your need, see https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_css_position
position is used to get the position of the target element.

Instead you need to use something like prependTo.

$("button").on("click", function(){
  $(".move").prependTo("#wrapper")
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#wrapper {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
  <p>Hello World</p>
  <p class="move">move</p>
  <button>Change color</button>
</div>

Upvotes: 1

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

You can easily shift children around using the $.fn.siblings and $.fn.insertBefore functions.

The following jQuery plugin will allow you to move a child to the front of its siblings.

(function($) {
  $.fn.shiftChild = function($target) {
    let $first = this.siblings().first();
    if ($target.get(0) !== $first.get(0)) {
      $target.insertBefore($first);
    }
    return this;
  }
})(jQuery);


$('.nav-menu').on('click', (e) => {
  $('.nav-menu').shiftChild($(e.target));
});
#nav {
  background: #aaa;
  padding: 2px;
}

.nav-menu {
  display: inline-block;
  width: 80px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  background: #ddd;
  margin: 2px 2px;
}

.nav-menu:first-child {
  background: #fff;
}

.nav-menu:not(:first-child) {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="nav"><!--
  --><div class="nav-menu" id="nav-account">Account</div><!--
  --><div class="nav-menu" id="nav-mobile">Mobile</div><!--
  --><div class="nav-menu" id="nav-help">Help</div>
</div>

Upvotes: 1

Related Questions