I write the Jquery code for getting all class names of a div when the page scroll.
This is the Jquery code–
$(window).scroll(function () {
if ($(window).scrollTop() > stickySidebar) {$('.nav-container').addClass('f-nav');}
else {$('.nav-container').removeClass('f-nav');}
//Get list of CSS class names
var classNames = $("#view").attr("class").toString().split(' ');
$.each(classNames, function (index, item) {
if (item === 'show') {
$(window).scroll(function() {
if ($(window).scrollTop() > 1180) {$('.nav-container').addClass('f-nav');}
else {$('.nav-container').removeClass('f-nav');}
});
}else{
$(window).scroll(function() {
if ($(window).scrollTop() > stickySidebar) {$('.nav-container').addClass('f-nav');}
else {$('.nav-container').removeClass('f-nav');}
});
}
});
});
This code is working fine but the problem is when I do inspect element then it shows error "
Uncaught TypeError: Cannot read property ‘toString’ of undefined
".
So please tell me that how I remove this error.
Thank you.
This means that #view either doesn’t exist or it doesn’t have any classes; you’d need to check this before attempting to split() them (note that toString() is redundant anyway). Like e.g.
var classNames = $('#view').attr('class');
var classArray = classNames ? classNames.split(' ') : [];
BTW, you’'re adding a new scroll event listener for each class each time you scroll… this can’t be right. I think you can simply remove those inner scroll handlers.
var classNames = $("#view").attr("class").toString().split(' ');
As you can see you are attaching the .toString() method on .attr() method and it’s reduntant, because .attr() method return the string value, so basically you are trying convert string to string.
So try this
var classNames = $("#view").attr("class").split(' ');
I already try this => var classNames = $(“#view”).attr(“class”).split(’ ');
but when I use this then it shows this error => Uncaught TypeError: Cannot read property ‘split’ of undefined