I am trying to stick the ads on website while user scroll it, using the code below
//to Stick Ads while scroll on Desktop
var StickHead=$('#StickHead').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > stickyHeaderTop) {
$('#StickHead').css({ position: 'fixed', top: '0px' });
} else {
$('#StickHead').css({ position: 'static', top: '0px' });
}
});
this code work's fine when we have div with id StickHead, but it throws an error when there is no StickHead id, as it would be difficult to copy paste it in selected page I have placed this code in script which is on all pages, now my question how can I make it work in all pages without error?
I have thought it would be easier if I can find if the Id exists, then run this code, otherwise leave it.
I have idea but not able to implement, any help?
thanks
Using Pure Javascript, you can check if element exists as below:
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// Yes Element Exists.
}
OR
You can use jQuery function length()
to check if there any element with associated class/div, with code like
if ($("#ElementId").length == 0) {
//Element does not exist, if value is greater than 0, element exists
//.length() gives the size of number of elements associated with particular id/class in html
}
Check this url fore more details
For your code, you can use this:
//to Stick Ads while scroll on Desktop
var StickHead= 0;
if ($("#StickHead").length != 0) {
StickHead= $('#StickHead').offset().top;
}
$(window).scroll(function () {
//in your code i think you are pointing 'StickHead' instead of 'stickyHeaderTop'
if ($(window).scrollTop() > StickHead) {
$('#StickHead').css({ position: 'fixed', top: '50px' });
} else {
$('#StickHead').css({ position: 'static', top: '0px' });
}
});
it should work, let me know, thank you
To check if element exists
Using jQuery:
if( $('#ElementToFind').length ) // use Id as selector
{
// yes element exists
}
if( $('.ElementToFind').length ) // use Class as selector
{
// yes element exists
}
You can also use JQuery Array Notation to check if element exists
var elemnt = $('.ElementClass')[0];
if (elemnt ) {
console.log('element found', elemnt );
}
Using JavaScript:
if(document.querySelectorAll("#element ").length){
//element Exists
}
OR
if (document.getElementById('ElementId') instanceof Object){
// Element found, do something here
}
Using Plain javascript, you can check if element exists or not
//you can use it for more advanced selectors
if(document.querySelectorAll("#yourID").length){
}
if(document.querySelector("#yourID")){
}
//you can use it if your selector has only an Id attribute
if(document.getElementById("yourID")){
// element exists
}
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly