How to truncate the anchor tag if tags are more than two

Viewed 82

I have the below code on my page

var menuBreadcrumb = document.getElementById('menu-breadcrumb');

var counta = $("#menu-breadcrumb a").length;
//alert(counta);

if (counta >= 2) {
  let mbcElement = '<a class="mbc-link-back" href="#" data-menu-item-id="">...</a>';
  menuBreadcrumb.insertAdjacentHTML('beforeend', mbcElement);


}
.mbc-link-back {
  color: #0066cc;
  text-decoration: none;
}

#menu-breadcrumb a+a::before {
  color: #222;
  content: '>';
  cursor: default;
  padding: 0 3px;
}
<div id="menu-breadcrumb">
  <a href="">Demo 1</a>
  <a href="">Demo 2</a>
  <a href="">Demo 3</a>
  <a href="">Demo 4</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

What I am doing is, If the anchor tag is more than 2 then I have to show first and the last anchor tag and in the middle, I have to show ... with clickable.

As of now, I have more than 2 anchor tags so my expected output is

Demo1 > ... > Demo4

If I have 2 anchor tags then I have to show

Demo1 > Demo2
1 Answers

You can use this script to achieve your goal:

let anchors = $("#menu-breadcrumb a");
  if (anchors.length > 2) {
    let mbcElement = $('<a class="mbc-link-back" href="#" data-menu-item-id="">...</a>');
    anchors.not(':first, :last').addClass('inactive');
    anchors.first().after(mbcElement)
  }
.mbc-link-back {
  color: #0066cc;
  text-decoration: none;
}

.mbc-link-back {
  color: #0066cc;
  text-decoration: none;
}

#menu-breadcrumb a+a::before {
  color: #222;
  content: '>';
  cursor: default;
  padding: 0 3px;
}

#menu-breadcrumb .inactive {
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="menu-breadcrumb">
  <a href="">Demo 1</a>
  <a href="">Demo 2</a>
  <a href="">Demo 3</a>
  <a href="">Demo 4</a>
</div>

If you want to show hidden links by click on ... you can add event listener on mbcElement like this:

mbcElement.on('click', function(){
  $(this).hide()
  $("#menu-breadcrumb a.inactive").removeClass('inactive')
})
Related