Reputation: 143
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
Upvotes: 0
Views: 33
Reputation: 780798
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
Upvotes: 2
Reputation: 2201
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.
Upvotes: 0