astroXoom astroXoom - 4 months ago 18
Javascript Question

Change the title of the page according to the title of a division

When a specified element is visible to viewport, the title of the page will change because of the element is visible to viewport, but how can I change the title according to the 'title' of a division

This is the jsFiddle, Feel free copy paste it to try it tho

Live Viewing/Testing for Results

(Some of the codes are from the GitHub repo "jQuery.isOnScreen"; I don't claim the right to say it that it is mine, but i'm trying to use it and modify it for my website, kudos to the original dev :D)

By the way, here is the javaScript code:


// This Gets the Article Title from a Division!

$.fn.is_on_screen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();

var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};

if( $('.target').length > 0 ) { // if target element exists in DOM
if( $('.target').is_on_screen() ) { // if target element is visible on screen after DOM loaded
document.title = "An Article"; // show this if visible
} else {
document.title = "Prospekt | A Gaming Community"; // show this if NOT visible
}
}
$(window).scroll(function(){ // bind window scroll event
if( $('.target').length > 0 ) { // if target element exists in DOM
if( $('.target').is_on_screen() ) { // show this if it's visible to dom
document.title = 'It is Magic! | Stackoverflow'; // show this if visible
} else {
document.title = "Prospekt | A Gaming Community"; // show this if not visible
}
}
});

Answer

The solution I got is to replace this code

if( $('.target').length > 0 ) { // if target element exists in DOM
if( $('.target').is_on_screen() ) { // if target element is visible on screen after DOM loaded
  document.title = "An Article"; // show this if visible
} else {
    document.title = "Prospekt | A Gaming Community"; // show this if NOT visible
}} 
$(window).scroll(function(){ // bind window scroll event
if( $('.target').length > 0 ) { // if target element exists in DOM
    if( $('.target').is_on_screen() ) { // show this if it's visible to dom
        document.title = 'It is Magic! | Stackoverflow'; // show this if visible
    } else {
    document.title = "Prospekt | A Gaming Community"; // show this if not visible
    }
}
});

With this code:

$(window).scroll(function(){ // bind window scroll event
        if( $('.target').length > 0 ) { // if target element exists in DOM
if( $('.target').is_on_screen() ) { // if target element is visible on screen after DOM loaded
  document.title =  $('.target')[0].title; // changes the document title to the target title.
}}});
Comments