Question

Consider the following html for a link in a navigation menu:

 <a id="mainLink" href="#");">A Main Link</a>

What I would like to do is when the device width is 320px or less, I want to add a couple of attributes to elements with the id of mainLink, so the resulting code looks like this:

 <a data-toggle="collapse" data-target=".navbar-collapse" id="mainLink" href="#">A Main Link</a>

My thinking was to follow some examples I have seen today and create a function:

<script type="text/javascript">
function addToggle () {
$(window).resize(function() {
    $("#mainLink").attr('data-toggle', 'collapse');
    $("#mainLink").attr('data-target', '.navbar-collapse');
});
}
</script>

But, I am a little confused on what that function should check for? I think the link below suggests a good approach but more help would be much appreciated. Thanks!

jquery if width is less than, change this attr

Was it helpful?

Solution

You are very close.

$(window).on("resize", function () {
  if($(window).width() <= 320) {
    $("#mainLink").attr({
      'data-toggle': 'collapse',
      'data-target': '.navbar-collapse'
    });
  } else {
    $("#mainLink").removeAttr('data-toggle data-target');
  }
}

I want to add a couple of attributes to elements with the id of mainLink

You should never have more than one element with the same id. If you intend to have multiple elements with the same id you should change the id to a class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top