Reputation: 6316
I am having trouble on passing DOM element to a function in my custom plugin. As you can see I called eHeight(this);
in the $(window).scroll();
function and I am getting this error:
Uncaught TypeError: Cannot read property 'attr' of undefined
then I changed the this
to eHeight(elem);
and this time I am getting this error:
Uncaught ReferenceError: elem is not defined
How can I pass the selected element to the eHeight()
?
(function($) {
$.fn.boxHeight = function(options) {
var settings = $.extend({
elemHeight: null
}, options);
var start = 0;
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > start) {
eHeight(this);
}
start = st;
});
function eHeight() {
var elem = $.trim(elem.attr('id'));
elem = "#" + elem;
var theHeight = $(elem).height();
if ($.isFunction(options.elemHeight)) {
options.elemHeight.call();
}
options.elemHeight.call();
}
};
})(jQuery);
$('#c').boxHeight({
elemHeight: function() {
$('#result').html('The Height is: ');
}
});
div {
height: 600px;
width: 100%;
}
#c {
background-color: khaki;
}
#result {
position: fixed;
right: 0;
top: 0;
background: yellow;
height: 40px;
width: 220px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='a'>A</div>
<div id='b'>B</div>
<div id='c'>C</div>
<div id='d'>D</div>
<div id='e'>E</div>
<div id='f'>F</div>
<div id='result'></div>
Upvotes: 0
Views: 130
Reputation: 1
Define a variable referencing this
element within plugin, and parameter expected at elemHeight
, pass the reference to elemHeight
. $.trim()
and call .call()
calls are not necessary
(function($) {
$.fn.boxHeight = function(options) {
var elem = this;
var settings = $.extend({
elemHeight: null
}, options);
var start = 0;
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > start) {
eHeight(elem);
}
start = st;
});
function eHeight(elem) {
var theHeight = elem.height();
if ($.isFunction(options.elemHeight)) {
options.elemHeight(theHeight);
}
}
};
})(jQuery);
$('#c').boxHeight({
elemHeight: function(theHeight) {
$('#result').html('The Height is: ' + theHeight);
}
});
div {
height: 600px;
width: 100%;
}
#c {
background-color: khaki;
}
#result {
position: fixed;
right: 0;
top: 0;
background: yellow;
height: 40px;
width: 220px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='a'>A</div>
<div id='b'>B</div>
<div id='c'>C</div>
<div id='d'>D</div>
<div id='e'>E</div>
<div id='f'>F</div>
<div id='result'></div>
Upvotes: 1