jQuery .load (or $.ajax) to get and set page title? - javascript

So far...
$('#container').load(hash + ' #page','', function() {
$('#container').fadeIn('fast');
document.title = $('#title').load(hash + ' #title').text();
});
...doesn't work.
Is there a better/correct way to do this?
FYI: -
I've added the ID #title the tag (all pages/it's a PHP template).
The container is .fade(ed)Out beforehand (less important)
Thanks in advance.

The problem is that, at the time you assign to document.title, the $('#title').load(hash + ' #title').text() might not have finished yet. Try setting the new document.title in the callback of that .load.
UPDATE
Try:
$('#container').load(hash + ' #page','', function() {
$('#container').fadeIn('fast');
$('#title').load(hash + ' #title', '', function(data) {
document.title = $(this).text();
});
});

I had the same requirement, to update the title for the page after ajax loads and that's what I used – one request, no need to set special attributes in your HTML:
var contentWrap = $('#content-wrap'),
contentId = '#content';
$.ajax({
url: hash.replace(/^#!\//, '') + '.html',
success: function(text) {
var oldContent = contentWrap.find(contentId),
newPage = $(text),
newContent = newPage.find(contentId);
oldContent.remove();
contentWrap.append(newContent);
// Set New Title
document.title = newPage.filter('title').text();
}
});

Do this :
$('#container').load(hash + ' #page','', function(result) {
$('#container').fadeIn('fast');
document.title = $(result).find('#title').text();
});
:)

We wanted to have an effect such that when someone visits our website, one should see the individual page's Title but when you move away, you can see "We'll still miss you... :)" using the below code:
<!-- Active Navigation Script -->
<script>
var url = window.location;
$('ul.nav a[href="'+ url +'"]').parent().addClass('active');
$('ul.nav a').filter(function() {
return this.href == url;
}).parent().addClass('active');
</script>
<!-- Tab Title change Script -->
<script>
$(function() {
// Get page title
var pageTitle = $("title").text();
// Change page title on blur
$(window).blur(function() {
$("title").text("We'll still miss you... :)");
});
// Change page title back on focus
$(window).focus(function() {
$("title").text(pageTitle);
});
});
</script>
You can see this in action here: http://www.solutelabs.com

Try below code:
.**filter**('title').text()
$('#container').load(hash + ' #page','', function(result) {
$('#container').fadeIn('fast');
document.title = $(result).filter('title').text();
});

Related

Hide print button when using PDFObject with PDF.js

I'm trying the print button and others when rendering a file using pdf.js. I tried using CSS and it works for Chrome but not Internet Explorer. For Internet Explorer I used javascript. JS works when I load one file but subsequent files are still showing the buttons.
viewer.html
<script type="text/javascript">
$(function () {
$('#print').hide();
$('#viewBookmark').hide();
$('#openFile').hide();
});
</script>
viewer.css
button#openFile, button#print, a#viewBookmark {
display: none;
}
default.cshtml
$('.file').on('click touchend', function (e) {
e.preventDefault();
if ($(this).hasClass('disabled'))
return;
var path = $(this).data('path').replace("\\\\", "http://").replace("#pdfFolder", "Uploads");
var name = $(this).data('name');
var lastname = $(this).data('lastname');
name = name.length > 8 ?
name.substring(0, 5) + '...' :
name.substring(0, 8);
lastname = lastname.length > 8 ?
lastname.substring(0, 5) + '...' :
lastname.substring(0, 8);
var tabCount = $('#tabs li').size();
var uuid = guid();
$(this).attr('data-position', uuid);
$('#content').css('display', 'block');
if (tabCount === 5) {
$('#maximumTabsModal').modal('show');
} else {
$(this).addClass('disabled')
$('<li role="presentation" data-position="' + uuid + '">' + name + '<span class="close"></span><br/>' + lastname + '</li>').appendTo('#tabs');
$('<div class="tab-pane" id="panel' + uuid + '"><div id="pdf' + uuid + '" class="pdf"></div></div>').appendTo('.tab-content');
$('#tabs a:last').tab('show');
var options = {
//pdfOpenParams: {
// view: "FitV"
//},
forcePDFJS: true,
PDFJS_URL: "pdfjs/web/viewer.html"
};
var pdf = PDFObject.embed(path, '#pdf' + uuid, options);
$('#print').hide();
$('#viewBookmark').hide();
$('#openFile').hide();
$('#exd-logo').hide();
}
});
Unfortunately, PDFObject is not capable of hiding the print button, it only provides a mechanism for specifying PDF Open Parameters, which do not include the ability to hide the print button.
I'm no expert on PDF.js, but since it's all JS-based, and hosted on your domain (i.e. you have full script access), you should be able to find a way to hack it to remove the print button. Good luck!
I was able to get the buttons to hide by handling the pagerendered event that PDF.js provides.
viewer.html
<script type="text/javascript">
$(function () {
document.addEventListener("pagerendered", function (e) {
$('#print').hide();
$('#viewBookmark').hide();
$('#openFile').hide();
});
});
</script>
I am shooting in the dark here because I do not know if the PDF viewer loads in an <iframe> or not, but the following code will scan over the page indefinitely and suppress the print button from showing if it finds it.
var $printSearch = setInterval(function() {
if ($('#print').length > 0 || $('#print').is(':visible')) {
hidePrint();
} else {
//doNothing
console.log('Searching...');
}
}, 150);
function hidePrint() {
$('div#print').css('display', 'none');
}
If it does load in an iframe we could use the .contents() and .filter() jQuery methods to target those elusive buttons.
Have you tried using print media queries ?

How do I have an event filter a page?

I'm working on a twitter clone in JS + jQuery for a pre-course to a development program, so if this is an obvious fix - let me know!
I have a problem I'm unable to solve: "click on username, page returns with that user's last tweets".
The only thing I could come up with is, an event handler on the <a> tag filter the page. However I'm vastly inexperienced and unclear in how to proceed.
Any ideas?
note- I removed some code for brevity.
$(document).ready(function() {
var $body = $('body');
$body.html();
var stream = function() {
var index = streams.home.length - 1;
while (index >= 0) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweetbody"></div>');
$tweet.text(': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
var link = $('<a>', {
text: tweet.user,
href: '#',
}).prop('outerHTML');
$tweet.html('#' + link + ': ' + tweet.message);
}
};
Here's the <a> tag event:
//click on a username to see that user's timeline.
$('a').on('click', function() {
console.log("a tag is clicked ");
console.log(this);
});
}();
}); //end document ready body
In the on click function you could perhaps do either of the two things, so go to another page, like redirecting to a new page
//click on a username to see that user's timeline.
$('a').on('click', function() {
//console.log("a tag is clicked ");
//console.log(this);
window.location = '/some_file.php?get_tweets='+tweet.user;
});
or, use an ajax call to do the same:
//click on a username to see that user's timeline.
$('a').on('click', function() {
//console.log("a tag is clicked ");
//console.log(this);
$.ajax({
type: "GET",
url: "/some_file.php",
data: {
'user' : tweet.user
},
success: function(msg) {
$body.html(msg);
});
});
In both cases some_file.php should format the content.

Page loading is gradually getting slower using jQuery script

I'm using this jQuery script to show search results. Everything works fine, but when search results have more than one page and I'm browsing pages via paging then every page loading is gradually getting slower. Usually first cca 10 pages loads I get quickly, but next are getting avoiding loading delay. Whole website get frozen for a little while (also loader image), but browser is not yet. What should be the problem?
function editResults(def) {
$('.searchResults').html('<p class=\'loader\'><img src=\'images/loader.gif\' /></p>');
var url = def;
var url = url + "&categories=";
// Parse Categories
$('input[name=chCat[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
url = url + "&sizes=";
// Parse Sizes
$('input[name=chSize[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
url = url + "&prices=";
// Parse Prices
$('input[name=chPrice[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
$('.searchResults').load('results.php'+url);
$('.pageLinks').live("click", function() {
var page = this.title;
editResults("?page="+page);
});
}
$(document).ready(function(){
editResults("?page=1");
// Check All Categories
$('input[name=chCat[0]]').click(function() {
check_status = $('input[name=chCat[0]]').attr("checked");
$('input[name=chCat[]]').each(function() {
this.checked = check_status;
});
});
// Check All Sizes
$('input[name=chSize[0]]').click(function() {
check_status = $('input[name=chSize[0]]').attr("checked");
$('input[name=chSize[]]').each(function() {
this.checked = check_status;
});
});
// Edit Results
$('.checkbox').change(function() {
editResults("?page=1");
});
// Change Type
$(".sort").change(function() {
editResults("?page=1&sort="+$(this).val());
});
});
$('.pageLinks').live("click", function() {
var page = this.title;
editResults("?page="+page);
});
just a wild guess but... wouldn't this piece of code add a new event handler to the click event instead reaplacing the old one with a new one? causing the click to call all the once registered handlers.
you should make the event binding just once
var global_var = '1';
function editResults(def) {
// all your code
global_var = 2; // what ever page goes next
};
$(document).ready(function() {
// all your code ...
$('.pageLinks').live("click", function() {
var page = global_var;
editResults("?page="+page);
});
});

Change div content and hash url

I made a fully functional Ajax Content Replacement script. The problem is that it adds forwards like /#about or /#work or /#contact to the adress but when I reload the site, the main page will be show. Why? How is it possible that when i type in the adress the right subpage will be show?
Someone told me that the problem is that I added the file manually when I use popstate. So I want a solution without popstate. I am not a Javascript expert but I would like to learn it. Because popstate but this is very circuitous.
window.location.hash = $(this).attr('href');
My .html files are in stored in /data/. The strange thing is that it finds the file but when I try to find it manually,the page show the main page or when I refresh the site with F5 the main page will be show,too.
Can you help me and show me how it works. We can use my code to find the error. Thanks a lot.
Here is the Websitelink : Demo Link
function refreshContent() {
var targetPage = 'home';
var hashMatch = /^#(.+)/.exec(location.hash);
// if a target page is provided in the location hash
if (hashMatch) {
targetPage = hashMatch[1];
}
$('#allcontent').load('data/' + targetPage + '.html');
}
$(document).ready(function(){
refreshContent();
window.addEventListener('hashchange', refreshContent, false);
$('.hovers').click(function() {
var page = $(this).attr('href');
$('#allcontent').fadeOut('slow', function() {
$(this).animate({ scrollTop: 0 }, 0);
$(this).hide().load('data/' + page +'.html').fadeIn('normal');
});
});
});
$('.hovers').click(function() {
window.location.hash = $(this).attr('href');
$.get('data/'+this.href, function(data) {
$('#allcontent').slideTo(data)
})
return false
})
You should load the initial page based on location.hash (if provided) on page load:
function refreshContent() {
var targetPage = 'home';
var hashMatch = /^#!\/(.+)/.exec(location.hash);
// if a target page is provided in the location hash
if (hashMatch) {
targetPage = hashMatch[1];
}
$('#allcontent').load('data/' + targetPage + '.html');
}
$(document).ready(function(){
refreshContent();
...
You can make back and forward work by listening to the Window.onhashchange event:
window.addEventListener('hashchange', refreshContent, false);
Do note that this doesn't work in Internet Explore 7 or lower.
Edit:
Okay, try this:
var $contentLinks = null;
var contentLoaded = false;
function refreshContent() {
var targetPage = 'home';
var hashMatch = /^#(.+)/.exec(location.hash);
var $content = $('#allcontent');
// if a target page is provided in the location hash
if (hashMatch) {
targetPage = hashMatch[1];
}
// remove currently active links
$contentLinks.find('.active').removeClass('active');
// find new active link
var $activeLink = $contentLinks.siblings('[href="' + targetPage + '"]').find('.navpoint');
// add active class to active link
$activeLink.addClass('active');
// update document title based on the text of the new active link
window.document.title = $activeLink.length ? $activeLink.text() + ' | Celebrate You' : 'Celebrate You';
// only perform animations are the content has loaded
if (contentLoaded) {
$content
.fadeOut('slow')
.animate({ scrollTop: 0 }, 0)
;
}
// after the content animations are done, load the content
$content.queue(function() {
$content.load('data/' + targetPage + '.html', function() {
$content.dequeue();
});
});
if (contentLoaded) {
$content.fadeIn();
}
contentLoaded = true;
}
$(document).ready(function() {
$contentLinks = $('.hovers');
refreshContent();
window.addEventListener('hashchange', refreshContent, false);
$contentLinks.click(function(e) {
e.preventDefault();
window.location.hash = '!/' + $(this).attr('href');
});
});

How to suppress JavaScript function with eg. hasClass?

I'm building on a WordPress theme and wants to load posts and pages with AJAX. I got that sorted out through the snippet below, but now I just need to suppress the function when clicking on the logo, obviously linking to the home url. So when clicking on the logo it should force a normal reload, instead of using the function.
I figure it would have something to do with "if hasClass(logo) then use default"... Yeah, I'm fairly new to JavaScript, but I have been searching a lot, so any help in the right direction will be much appreciated. Thanks!
The snippet:
$(".home li.home").removeClass("home").addClass("current_page_item");
var $wrapperAjax = $("#wrapper-ajax"),
URL = '',
siteURL = "http://" + top.location.host.toString(),
$internalLinks = $("a[href^='"+siteURL+"']"),
hash = window.location.hash,
$ajaxSpinner = $("#ajax-loader"),
$el, $allLinks = $("a");
function hashizeLinks() {
$("a[href^='"+siteURL+"']").each(function() {
$el = $(this);
if ($.browser.msie) {
$el.attr("href", "#/" + this.pathname)
.attr("rel", "internal");
} else {
$el.attr("href", "#" + this.pathname)
.attr("rel", "internal");
}
});
};
hashizeLinks();
$("a[rel='internal']").live("click", function() {
$ajaxSpinner.fadeIn();
$wrapperAjax.animate({ opacity: "0.1" });
$el = $(this);
$(".current_page_item").removeClass("current_page_item");
$allLinks.removeClass("current_link");
URL = $el.attr("href").substring(1);
URL = URL + " .entry";
$wrapperAjax.load(URL, function() {
$el.addClass("current_link").parent().addClass("current_page_item");
$ajaxSpinner.fadeOut();
$wrapperAjax.animate({ opacity: "1" });
hashizeLinks();
});
});
$("#searchform").submit(function(e) {
$ajaxSpinner.fadeIn();
$wrapperAjax.animate({ opacity: "0.1" });
$el = $(this);
$(".current_page_item").removeClass("current_page_item");
$allLinks.removeClass("current_link");
URL = "/?s=" + $("#s").val() + " .entry";
$wrapperAjax.load(URL, function() {
$ajaxSpinner.fadeOut();
$wrapperAjax.animate({ opacity: "1" });
hashizeLinks();
});
e.preventDefault();
});
if ((hash) && (hash != "#/")) {
$("a[href*='"+hash+"']").trigger("click");
}
I'm guessing you mean the script from this line: $("a[rel='internal']")
In that case, $("a[rel='internal']").not('.logo') should do the trick.
I should've read the entire code. Replace $("a[href^='"+siteURL+"']") with $("a[href^='"+siteURL+"']").not('.logo') as well.
If it has the class .logo you could add this at the top of the function:
if ($(this).hasClass('logo')) return true;
See the simple example.

Categories