0

I need to add an href attribute to a element using jqueny when window size is less than 768 pixel

        <ul class="menu-link">
            <!--<li><a class="" href="#">HOME</a></li>-->
            <li><a id="#about-us" >ABOUT US</a></li>
            <li><a id="#contact" >CONTACT</a></li>
        </ul>

jQuery(document).ready(function ($) {
      var windowSize = $(window).width(); // 
            if (windowSize < 768) {
                //add attr
                $("#about-us").attr("href", "#about-us");
                $("#contact").attr("href", "#contact");
    }
});

It is not working for some reason am i doing something wrong

4
  • 4
    also you have id="#about-us" and id="#contact". It should just be id="about-us" and id="contact" Commented Jul 25, 2014 at 18:15
  • 3
    why don't you use media query? Commented Jul 25, 2014 at 18:15
  • Using media query then i have to repeat whole set of html code twice. for this reason i want to do it with jquery. Commented Jul 25, 2014 at 18:18
  • "It is not working for some reason am i doing something wrong" Yeah, i'm sure that's why it isn't working. Commented Jul 25, 2014 at 18:31

2 Answers 2

1

First of all you need to remove the # from the ids:

<li><a id="#about-us" >ABOUT US</a></li>
<li><a id="#contact" >CONTACT</a></li>

Should be

<li><a id="about-us" >ABOUT US</a></li>
<li><a id=contact" >CONTACT</a></li>

Next, you probably want to run that on window.resize as well:

$(function() {
  $(window).on('resize', function() {
    var add_remove = $(window).width() < 768; 
    $("#about-us").attr("href", add_remove ? "#about-us" : "");
    $("#contact").attr("href", add_remove ? "#contact" : "");
  });
  $(window).trigger('resize');
});
Sign up to request clarification or add additional context in comments.

Comments

1

to show what @pattmorter is pointing out

HTML:

<ul class="menu-link">
        <!--<li><a class="" href="#">HOME</a></li>-->

        <!-- remove the # from the ids -->
        <li><a id="about-us" >ABOUT US</a></li>
        <li><a id="contact" >CONTACT</a></li>
    </ul>

JS:

jQuery(document).ready(function ($) {
  var windowSize = $(window).width(); // 
        if (windowSize < 768) {
            //add attr
            $("#about-us").attr("href", "#about-us");
            $("#contact").attr("href", "#contact");
        }
});

2 Comments

Thanks, I just made a stupid mistake... didn't notice that i am adding # with id=#about-us.. stress of overwork..
I think we have all been there... Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.