0

So I am having an issue running a function via .each, It jQuery doesn't seem to be picking up the element in question via 'this'. Code below: (Edit: I am attempting to centre something regardless of screen width absolutely for multiple elements)

$(document).ready(function(){
    $('.main-feature h1').each(function() {
        centerThis();
    });
    $('.meta-feature h2').each(function() {
        centerThis();
    });
});//doc-rdy
function centerThis(){
    var trackHeight = $(this).height()/2;
    var trackWidth = $(this).width()/2;
    var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
    var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
    $(this).css({
        "margin-left": -pxInEmsWidth+'em',
        "margin-top": -pxInEmsHeight+'em'
    });
    $(window).resize(function(){
        var trackHeight = $(this).height()/2;
        var trackWidth = $(this).width()/2;
        var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
        var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
        $(this).css({
            "margin-left": -pxInEmsWidth+'em',
            "margin-top": -pxInEmsHeight+'em'
        });
    });
}//centerThis

2 Answers 2

2

You should pass this as an argument to the centerThis function:

$(document).ready(function(){
    $('.main-feature h1').each(function() {
        centerThis(this);
    });
    $('.meta-feature h2').each(function() {
        centerThis(this);
    });
});//doc-rdy
function centerThis(elem){
    var trackHeight = $(elem).height()/2;
    var trackWidth = $(elem).width()/2;
    var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
    var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
    $(elem).css({
        "margin-left": -pxInEmsWidth+'em',
        "margin-top": -pxInEmsHeight+'em'
    });
    $(window).resize(function(){
        var trackHeight = $(this).height()/2;
        var trackWidth = $(this).width()/2;
        var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
        var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
        $(this).css({
            "margin-left": -pxInEmsWidth+'em',
            "margin-top": -pxInEmsHeight+'em'
        });
    });
}//centerThis
1
  • Thanks Barmar, hole in one! Ill up the vote in 8m :) Sep 1, 2014 at 15:49
0

You have to give it as a parameter to the function centerThis() you are calling and replace $(this) in the function with the name of the input parameter.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.