Scroll to certain div with url - javascript

Can i send the request to load certain div with a url only something like abc.com/#header1 cause the approach i am using i have to make 5 separate files for my task and update all of them.
If it can be done by including any piece of code in my one file then it'll be best for me.
I want the scroll on div with the url request something like abc.com/#def where def is the id of the div the page should load.

In relation to your previous question, this is how you can do it:
$(function(){
// get hash value
var hash = window.location.hash;
// now scroll to element with that id
$('html, body').animate({ scrollTop: $(hash).offset().top });
});
You need to put that code in page where you want element to scroll. So if you visit yourdomain.com/#foo, it would scroll to an element with id set to foo.

You can use jQuery to load some url in particular div within the page.
Here is an example with fraction of code :
$('#result').load('test.html', function() {
alert('Hello,I am in the div');
});
If you need the data of that particular url to be shown.Then,you can use Ajax along with Jquery.
Here is a small code for it:
$(document).ready(function(){
$("#result").load(function(){
$.ajax({
type: 'GET',
url: "http://localhost/a.html",
success:function(data){
alert(data);
}
});
return false;
});
});
Hope this helps you.

try this : document.getElementById('elmID').scrollIntoView(true);

Related

Jquery how to execute commands appended with ajax

I'm loading the content of a document into a div when I click one item of the menu. This foreign document contains jQuery commands. But is not running.
$(document).ready(function() {
$("ul.subnav li a").click(function() {
link = $(this).attr("href");
$.ajax(link).done(function(data) {
$("#div-page").html(data);
});
return false;
});
});
In the document that will be loaded there is more jQuery commands like this:
$(document).ready(function() {
// get lista de estados
$.ajax("../php/get_lista_estados.php").done(function(data) {
$("#estados").append(data);
});
$("#estados").change(function() {
id = $(this).val();
// get lista de estados
$.ajax("../php/get_lista_municipios.php?id=" + id).done(function(data) {
$("#municipios").html(data);
});
});
});
But when I load this document into div the commands don't run. Do I speak clear?
When it comes to jQuery and Ajax combined - it is important to understand how JavaScript is being implemented on DOM while script loads.
The reason why you are seeing answers suggesting using $.getScript() or to add <script src="your.js"></script> is because, once DOM is loaded - then that's it. If you wanted addition functions to be fired as long as it is coming from external script via ajax, just like what you are trying to do. You are attempting to load new function to 'already-loaded' DOM - and it's not how it works.
If you want any functions to respond to the ajax injection, then you need to have your script to be among those that get preloaded when DOM is run. So, that's how $.getScript() comes into the picture.
Usually, with that kind of injection you want to do, you will want to use $.getScript() to fetch your javascript functions / definitions, meanwhile your ajax to get/post the script that contains your HTML structures. You will be able to do this fancy injection in this method and play it around with jQuery.
You can use $.getScript to load and run it. Read the jQuery docs for more info
Example:
$.getScript("test.js", function(){
alert("Running test.js");
});
Use jQuery.getScript() or:
$(document).ready(function() {
$("ul.subnav li a").click(function(e) {
e.preventDefault();
link = $(this).attr("href");
$.ajax({
url: link,
dataType: "script"
}).done(function(data){
// No need to append data as the script has already been loaded and run.
// $("#div-page").html(data);
// Do any other stuff here..
});
});
});

Jquery link and URL hash

I'm new at jQuery and don't really know what I'm doing. I need some help.
I'm creating a web app. It has a header and footer that I want to stay on every page, so I decided to use jQuery to load a page into the main content div so every time a link is clicked, the whole page isn't reloaded.
Here's what I'm using to accomplish this:
<script>
$(function() {
$("a.ajax-link").on("click", function(e) {
e.preventDefault();
$("#main_content").fadeOut('fast');
$("#main_content").load(this.href);
$('html, body').animate({ scrollTop: 0 }, 0);
$("#main_content").fadeIn('fast');
});
});
</script>
And each link:
<a class="ajax-link" id="add" href="add.php"><span class="glyphicon glyphicon-plus-sign" style="margin-top:4px;"></span><div>add</div></a>
This works great EXCEPT the page address. My app uses PHP, and I need to be able to PHP Header to a page like 'index.php#about' that will load the index.php page and display the about.php in the #main_content div.
I tried this:
<script type="text/javascript">
$(document).ready(function(){
var id = window.location.hash;
$(id).trigger('click');
})
</script>
I can see where the link is selected (box around it), but it doesn't actually click it. I'm not sure why.
Thank you in advance for any help!
I think you could just get the hash, add a php extension and make an ajax call.
<script>
$(function() {
$("a.ajax-link").on("click", function(e) {
e.preventDefault();
// Get the hash from the URL and append .php extension
// index.php#about ==> 'about.php'
var page = window.location.hash + ".php";
//Make an ajax call using the page variable.
$("#main_content").fadeOut('fast');
$("#main_content").load(page);
$('html, body').animate({ scrollTop: 0 }, 0);
$("#main_content").fadeIn('fast');
});
});
</script>

Why is my div populated with my whole page?

I'm trying to load a div from another page using ajax but maintain the URL integrity using the History API. The ajax and history part is working (ie. the div is loading and the url is changing) but for some reason my div contains my entire page not just what is meant to be in the div!
This is the case for both the original page and the page div being loaded.
Stripped back HTML
<!DOCTYPE html>
<html>
<body>
<div id="slider">
... all the page content
<a rel='tab' href="p/password.jsf">Forgot password?</a>
</div>
</body>
</html>
JS
<script>
$(function(){
$("a[rel='tab']").click(function(e){
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({
url:pageurl + '?rel=tab',
success: function(data){
$('#slider').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
$('#slider').html(data);
}});
});
</script>
If you want to fetch an part of an page with ajax, then you can use the load method with the id of the element to fetch the content from.
$('#slider').load(pageurl + '?rel=tab #container_with_content_to_fetch', function() {
alert('callback after success.');
});
More info about load(): info
You may need to stop the default click action. It appears as though your link is acting as a... link.
$("a[rel='tab']").click(function(e){
e.preventDefault();
...
you if you want to select a specific part of the page that you recive with the ajax response
then do the following
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
var mydiv = $('#my_div_id' , data ) // this will get the div with an id of #my_div_id
$('#slider').html(mydiv );
}});
});
$.ajax loads the whole page. You can use .load()
Instead of
$.ajax({
url:pageurl + '?rel=tab',
success: function(data){
$('#slider').html(data);
}});
you can use
$('#slider').load(pageurl + ' [rel=tab]');
The docs are here.

Need help understanding how to ajaxify a web site

I recently found this gist on how to Ajaxify a Website with the HTML5 History API using History.js, jQuery and ScrollTo: https://github.com/browserstate/ajaxify
I am having a hard time getting a simple version of this working and am not sure I understand everything. First, I loaded all the scripts provided in the gist, then set up a really simple nav and content section:
<ul id="nav">
<li id="home-link">Home/</li>
<li id="work-link">Work/</li>
<li id="labs-link">Labs/</li>
<li id="blog-link">Blog/</li>
<li id="contact-link">Contact</li>
</ul>
<div id="content"></div>
Next, I changed the selector variables to match the html:
/* Application Specific Variables */
contentSelector = '#content',
$content = $(contentSelector),
contentNode = $content.get(0),
$menu = $('#nav'),
activeClass = 'active',
activeSelector = '.active',
menuChildrenSelector = 'li',
What I'm supposed to do next is where I get lost. All I want to do is load in html content specific to the nav link selected. So if I clicked "Work", I would like to load a work.html file into the content section and change the url to "mywebsite.com/work". To keep things easy lets say work.html and all other ajaxable content is located in the same directory.
Any help is greatly appreciated! Cheers!
So here is a real bare bones example of how I ended up ajaxifying the website I was working on that inspired this question. Sorry for the really long delay. First the HTML:
<ul id="nav">
<li id="home-link">Home</li>
<li id="work-link">Work</li>
<li id="labs-link">Labs</li>
<li id="blog-link">Blog</li>
</ul>
<div id="content">Home Content</div>
Next the Javascript:
<script type="text/javascript">
var directory = 'content/'; //directory of the content we want to ajax in
var state = History.getState();
//for when they click on an ajax link
$('.ajaxify').on('click', function(e){
var $this = $(this);
var href = $this.attr('href'); // use the href value to determine what content to ajax in
$.ajax({
url: directory + href + '.html', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
}
});
e.preventDefault(); // we don't want the anchor tag to perform its native function
});
//for when they hit the back button
$(window).on('statechange', function(){
state = History.getState(); // find out what we previously ajaxed in
$.ajax({
url: directory + state.title + '.html', //create our path
dataType: 'html',
success: function(data) {
$('#content').html(data);
}
});
});
</script>
Essentially all I am doing is intercepting anchor tag clicks with the class 'ajaxify' used to signal what specific content I want to load in. Once I intercept the click and determine what content to load, I then use history.js pushSate() to keep track of what order the user is going through the site and change the url without reloading the page. If they decide to hit the back button, the statechange listener will load in the correct content. If they decide to hit the refresh button, you will need to come up with a method of duplicating your index page with the different url names. This is easy to do in php or you could just copy, paste, and rename the index page as needed.
Here is an example I posted on Github: https://github.com/eivers88/ajaxify-simple-demo
Just a reminder, when working with ajax locally, it is best to run your projects on a personal web server like MAMP or WAMP. This demo will fail in chrome without a server running. However, it should work in firefox without a server.
There are a variety of things you would need to do given those requirements. Here is a function you can use:
function doAjax(htmlpage){
$.ajax({
url:"/"+htmlpage,
type: 'GET',
success: function(data){
$('#content').html(data)
}
});
}
The the simplest way to hook this out would be to adjust your tags above to be like:
<img>
It would however be slightly more "correct" (though functionally the same) to do this with jquery in a script tag at the top:
$(function () {
$('#buttonid1').click(function(){doAjax('work.html')});
$('#buttonid2').click(function(){doAjax('about.html')});
$('#buttonid3').click(function(){doAjax('contact.html')});
});
Note in both cases, these "work.html" pages shouldn't be full html documents, they should just be what goes in your content div.
This ajax will do nothing to change the url that your visitor sees. To get that to work, you'll have to use the html5 history api. It is quite a bit more complicated than the the ajax request I have above. So if you don't have a full mastery of what I wrote above, it may or may not be appropriate.

page transitions with jquery

I'd to create some transitions between pages. I've made it this way:
$("div.fading").css('display', 'none');
$("div.fading").fadeIn(500);
$("a.fade").click(function(event){
event.preventDefault();
link = event.href;
$("div.fading").fadeOut(500, redirect(link));
});
in redirect have I used window.location and it has been working, but the fadeIn effect has been running for every page which has been loaded. I didn't like that, so I'm trying make it with ajax. It should allow me to call the fadeIn function as a callback function in jquery. I have this code,
$(".fading").click(function(event){
event.preventDefault();
var link = this.href;
$(".fade").fadeOut(300, function(){
$.ajax({
url: link,
success: function(){
$(".fade").fadeIn(300);
}
});
});
which is not fully working..All effects are OK, but page which I get after fadeIn is simply the same that faded out..IMHO can I do it another way with .load() function, I tried to implement that, but there were too some problems:-)Does anybody know what I should do to make it fully working?Thanks..
You're calling the page via ajax, but you're not replacing the contents of the current .fade div before you call fadeIn(). I've modified your code to do that below. .load() should do the same thing a little cleaner.
$(".fading").click(function(event){
event.preventDefault();
var link = this.href;
$(".fade").fadeOut(300, function(){
$.ajax({
url: link,
success: function(pageHTML){
$(".fade").html(pageHTML);
$(".fade").fadeIn(300);
}
});
});
I think you're just missing any used of the data returned. In the success function you'll need to do something like:
$('.fade').html(data);
Then and you can fade it back in with the page having been updated.

Categories