SanJeet Singh
SanJeet Singh

Reputation: 1331

:target selector doesn't work

Here is my Markup:

<p>A paragraph with <a id="link" href="#link">a link</a> inside it.</p>

Here is my jQuery:

$("a:target").css("font-size","2em");

When I click on the link, the URL changes to http://example.com/file.html#link. However, the font-size does not increase. There is no change in font-size even if I directly load http://example.com/file.html#link

Why is the selector not working?

Update: I have to use the :target selector. There is no choice.

Upvotes: 2

Views: 366

Answers (1)

Mohammad
Mohammad

Reputation: 21499

This is your problem that you used :target selector immediately after anchor clicking. When you click on anchor, javascript run your selector immediately while browser doesn't focus on target element. You need to pause your code for miliseconds then run :target selector.

$("a").click(function(){
    setTimeout(function(){
        $("a:target").css("font-size","2em");
    }, 1); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
    A paragraph with 
    <a id="link" href="#link">a link</a>
    inside it.
</p>

Upvotes: 2

Related Questions