David Prieto
David Prieto

Reputation: 2299

$(':target') returns length 0 in Internet Explorer 11

I'm trying to compensate the anchor movement position in a web page so it's not covered by a fixed header.

I solved the problem with this anwser, and it works fine for every browser except IE. It just scrolls up a few pixels after the anchor movement.

The code is as follow:

(function($, window) {
    var adjustAnchor = function() {

        var $anchor = $(':target'),
                    fixedElementHeight = 160;
        console.log("Anchor: "+ JSON.stringify($anchor));

        if ($anchor.length > 0) {
            $('html, body')
                .stop()
                .animate({
                    scrollTop: $anchor.offset().top - fixedElementHeight
                }, 200);
        }
    };

    $(window).on('hashchange load', function() {
        adjustAnchor();
    });

})(jQuery, window);

Now, the output of the console.log in IE11 is this:

{
    "length": 0,
    "prevObject": {
        "0": {
            "__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR": false,
            "_html5shiv": 1,
            "jQuery1111049273906621767055": 4
        },
        "context": {
            "__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR": false,
            "_html5shiv": 1,
            "jQuery1111049273906621767055": 4
        },
        "length": 1
    },
    "context": {
        "__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR": false,
        "_html5shiv": 1,
        "jQuery1111049273906621767055": 4
    },
    "selector": ":target"
}

The problem is obviosly the "length": 0, which means is not selecting anything. Why is this? The :target selector should work fine in IE11 but jQuery doesn't grab it.

Excuse my ignorance in jQuery and my bad english.

Upvotes: 4

Views: 305

Answers (1)

David Prieto
David Prieto

Reputation: 2299

I solved the problem by adding id attributes beside the name attributes to the target of the anchors, like this:

<a class="anchor" name="condiciones" id="condiciones"></a> 

For some reason, the name attribute is enough for anchors to work in every browser, but in order to grab them with jQuery in Internet Explorer, anchors must be made with id attribute.

I hate IE.

Upvotes: 2

Related Questions