Home » Jquery » jquery – On click, targat not found-Exceptionshub

jquery – On click, targat not found-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have given below html and jquiry.
When click on link, that particular content to show. but it not works.
I can’t findout problem, can someone help me?

HTML

<div class="nav">
    <ul>
        <li id="about" data-targat=".about-info"><a href="#">about</a></li>
        <li><a id="work" data-targat=".work-info"><a href="#">work</a></li>
    </ul>
</div>

<div class="Content-wrapper">
    <div class="about-info content">
        <p>about info goes here</p>
    </div>
    <div class="work-info content">
        <p>work info goes here</p>
    </div>
</div>

jQuery

var $main = $(".Content-wrapper");
var $section = $(".content").hide();
$('.nav ul li').click(function(e) {
    e.preventDefault();
    $section.hide();
    var target = $(this).data('target');
    if(target){
        $section.filter(target).show();
    }
});
How to&Answer:
  1. You should listen to li event like $('.nav ul li').on("click", function(e)
  2. In HTML data-targat while in jQuery you are getting $(this).data('target')
  3. In second li <li><a id="work" is redundant a tag.
var $main = $(".Content-wrapper");
var $section = $(".content").hide();
$('.nav ul li').on("click", function(e) {
    $section.hide();
    var target = $(this).data('target');
    if(target){
        $section.filter(target).show();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav">
    <ul>
        <li id="about" data-target=".about-info"><a href="#">about</a></li>
        <li id="work" data-target=".work-info"><a href="#">work</a></li>
    </ul>
</div>

<div class="Content-wrapper">
    <div class="about-info content">
        <p>about info goes here</p>
    </div>
    <div class="work-info content">
        <p>work info goes here</p>
    </div>
</div>