SWFAddress: adding "/" char at the end of an URL via JavaScript - javascript

how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.
So something like this:
http://mysite.com/section
// and after click to a specific <a ="#">button</a> get
http://mysite.com/section/#/sub-content
// instead of
http://mysite.com/section#/sub-content
I've started with this code to do it:
$(".time_dot, .time_year").click (function () {
onClickEvent (this);
});
function onClickEvent (dom) {
var timer = setTimeout (function () {
SWFAddress.setValue($(dom).parent().attr("id"));
}, 200);
// do something else
}
The setTimeout method is used to avoid the <a> button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....
How can I do that?

As already said, you cannot change the URL without forcing a reload of the site. And I don't think you want that. (but it depends on how SWFAddress.setValue() actually works, if it just keeps track of the URLs internally (without changing the browsers URL) then you can do it)
But I wanted to give you an alternative for setTimeout:
$(".time_dot, .time_year").click (function (event) {
event.preventDefault();
event.stopPropagation();
onClickEvent (this);
});
function onClickEvent (dom) {
SWFAddress.setValue($(dom).parent().attr("id"));
// do something else
}
With this you prevent the click event from bubbling up and also prevent the change the default action (which would be following the link).
See jQuery event object.

You can't change the "path" part of the URL without reloading the page. So, if you're at http://mysite.com/section, you can not navigate to http://mysite.com/section/#/sub-content without reloading the page.

you mean like
$(".time_dot, .time_year").click (function () {
setTimeout (function () {
SWFAddress.setValue("/"+$(this).parent().attr("id")+"/");
}, 200);
});

function fixUrl(url) {
return url.replace(/\/?$/,'/');
}
//or
function fixUrl(url) {
return url.match(/\/$/)
? url
: url + '/';
}

Related

second this is wrong? [duplicate]

I'm not quite sure if I'm not using this in the correct scope or what, but I have a script that basically captures a link click and causes the page to fade out before going to the linked page. However, if the link is a JavaScript onclick, the script fails.
Here's my code:
<script type="text/javascript">
pageObj = {
init: function(){
$("body").fadeTo("slow", 1);
},
redirectPage: function(redirect){
window.location = redirect;
},
linkLoad: function(location){
$("body").fadeOut(1000, this.redirectPage(location));
}
};
$(document).ready(function() {
pageObj.init();
$("a").click(function(e){
e.preventDefault();
if (this.attr('onclick') !== undefined) {
eval(this.attr('onclick').val());
} else {
var location = this.href;
pageObj.linkLoad(location);
}
});
});
</script>
As you can see, I'm trying to do a check to see if the link has the onclick attribute, and then call the onclick function if it exists. How can I achieve this?
Use: $(this).attr instead of this.attr
This forces it into the context of jQuery.
While Diodeus is correct that you need to wrap this in a jQuery collection before using attr() (it's a method of a jQuery collection, not of an HTMLElement), you can just as well skip attr().
$("a").click(function(e){
var location;
e.preventDefault();
if ($.isFunction(this.onclick)) {
this.onclick.call(this, e);
} else {
location = this.href;
pageObj.linkLoad(location);
}
});
Note that I used the property (when an HTML document loads, attributes are usually preloaded into properties, with on_______ attributes being preloaded as methods. Also note that I used this.onclick.call() rather than eval(), setting the correct this for onclick methods, and ensuring access to the event object as an argument.

How to handle back button while changing the browser-URL with HTML5 pushState

I’ve made a one page site. When user clicks on the menu buttons, content is loaded with ajax.
It works fine.
In order to improve SEO and to allow user to copy / past URL of different content, i use
function show_content() {
// change URL in browser bar)
window.history.pushState("", "Content", "/content.php");
// ajax
$content.load("ajax/content.php?id="+id);
}
It works fine. URL changes and the browser doesn’t reload the page
However, when user clicks on back button in browser, the url changes and the content have to be loaded.
I've done this and it works :
window.onpopstate = function(event) {
if (document.location.pathname == '/4-content.php') {
show_content_1();
}
else if (document.location.pathname == '/1-content.php') {
show_content_2();
}
else if (document.location.pathname == '/6-content.php') {
show_content_();
}
};
Do you know if there is a way to improve this code ?
What I did was passing an object literal to pushState() on page load. This way you can always go back to your first created pushState. In my case I had to push twice before I could go back. Pushing a state on page load helped me out.
HTML5 allows you to use data-attributes so for your triggers you can use those to bind HTML data.
I use a try catch because I didn't had time to find a polyfill for older browsers. You might want to check Modernizr if this is needed in your case.
PAGELOAD
try {
window.history.pushState({
url: '',
id: this.content.data("id"), // html data-id
label: this.content.data("label") // html data-label
}, "just content or your label variable", window.location.href);
} catch (e) {
console.log(e);
}
EVENT HANDLERS
An object filled with default information
var obj = {
url: settings.assetsPath, // this came from php
lang: settings.language, // this came from php
historyData: {}
};
Bind the history.pushState() trigger. In my case a delegate since I have dynamic elements on the page.
// click a trigger -> push state
this.root.on("click", ".cssSelector", function (ev) {
var path = [],
urlChunk = document.location.pathname; // to follow your example
// some data-attributes you need? like id or label
// override obj.historyData
obj.historyData.id = $(ev.currentTarget).data("id");
// create a relative path for security reasons
path.push("..", obj.lang, label, urlChunk);
path = path.join("/");
// attempt to push a state
try {
window.history.pushState(obj.historyData, label, path);
this.back.fadeIn();
this.showContent(obj.historyData.id);
} catch (e) {
console.log(e);
}
});
Bind the history.back() event to a custom button, link or something.
I used .preventDefault() since my button is a link.
// click back arrow -> history
this.back.on("click", function (ev) {
ev.preventDefault();
window.history.back();
});
When history pops back -> check for a pushed state unless it was the first attempt
$(window).on("popstate", function (ev) {
var originalState = ev.originalEvent.state || obj.historyData;
if (!originalState) {
// no history, hide the back button or something
this.back.fadeOut();
return;
} else {
// do something
this.showContent(obj.historyData.id);
}
});
Using object literals as a parameter is handy to pass your id's. Then you can use one function showContent(id).
Wherever I've used this it's nothing more than a jQuery object/function, stored inside an IIFE.
Please note I put these scripts together from my implementation combined with some ideas from your initial request. So hopefully this gives you some new ideas ;)

Setting up form tracking with Jquery

I need to set up a custom script for tracking a users click through on a form submission field. This is what I've got so far. As the user navigates down through the form fields the counter variable (base) totals up how far along the path the user has reached. I want to send the results off when the user leaves the page by sending out the base variable. I'm thinking of using the .unload function in jQuery. However for some reason unload isn't responding the way I think it should. Any ideas?
var base = 0; //declares a variable of 0. This should refresh when a new user lands on the form page.
function checkPath(fieldNo, path) { //this function should check the current base value of the base variable vs the current fieldNo
if (fieldNo >= path) { //checks to see if base if lower than fieldNo
base = fieldNo; //if true, base is set to current fieldNo
return base;
} else {
return base; //if false, simply returns base.
}
};
$('#order_customer_fields_forename').focus(function () { //when the form box is selected should run checkPath then alert result.
checkPath(1, base);
});
$('#order_customer_fields_surname').focus(function () {
checkPath(2, base);
});
$('#order_customer_fields_postcode').focus(function () {
checkPath(3, base);
});
$('#order_customer_fields_address1').focus(function () {
checkPath(4, base);
});
$('#order_customer_fields_address2').focus(function () {
checkPath(5, base);
});
$(window).unload(function () {
alert(base);
});
The unload event fires too late for the effect you need. You should try using the onbeforeunload event using either vanilla Javascript:
window.onbeforeunload = function (e) {
// Your code here
};
Or jQuery:
$(window).bind('beforeunload', function (e) {
// Your code here
});
Either way, you should be aware that this is not an ideal solution for what you are trying to achieve. This event is implemented unevenly across browsers. Chrome seems to be the most restrictive, and IE the most permissive, in its implementation.
A different direction you may want to take is sending the data to the server by XHR whenever the user completes a field.

seperate 2 javascript file in asp.net page

i having a very weird problem now . I has separate 2 jquery js file with my aspx file.However the pageload doesn't seem like work.
Because I'm using UpdatePanel to asynchronously call a button click event in a page.
Therefore i attach my click event within the page load method
Here is the screen shoot of my js file
Here is the sample code for modalPopup.js
function pageLoad() {
//#region Search function
$("[id$=txtSearch]").keyup(function (e) {
"[id$=txtCurrentPage2]"
$("[id$=txtCurrentPage2]").val(1)
$("[id$=txtCurrentPage]").val(1)
$("[id$=hfCurrentTxt]").val(1)
var txtSearch = $("[id$=txtSearch]").val()
var pagesize = $("[id$=ddlRowPerPage]").val()
var skip = $("[id$=txtCurrentPage2]").val()
var type = $("[id$=hfGvType]").val()
sendData(txtSearch, skip, pagesize, type);
e.preventDefault();
});
//#endregion
The sample code for the ASPX.js
function pageLoad() {
$("[id$=txtCMemberID]").bind('keyup change', function (e) {
alert("hello");
e.preventDefault();
});
}
The modalPopup.js can work very smoothly, but the ASPX.js seem like doesn't work.Anyone face this problem before.? Please guide me some idea. Thanks
Offhand, I'd wager that you are loading ASPX.js first, and then loading modalPopup.js later in the page. Both files define a global function named pageLoad. As you cannot have two separate global functions that share the same name, one is redefining the other. Rename one of the functions (it doesn't have to be called pageLoad). Example as follows:
Change ASPX.js to:
function bindKeyUpChangeHandler() {
$("[id$=txtCMemberID]").bind('keyup change', function (e) {
alert("hello");
e.preventDefault();
});
}
then call bindKeyUpChangeHandler() in addition to pageLoad().
Instead of declaring like that why not use
Sys.Application.add_load(function () {
//do stuff on page load
});

Wait for iframe to load in JavaScript

I am opening an iframe in JavaScript:
righttop.location = "timesheet_notes.php";
and then want to pass information to it:
righttop.document.notesform.ID_client.value = Client;
Obviously though, that line isn't going to work until the page has fully loaded in the iframe, and that form element is there to be written to.
So, what is the best/most efficient way to address this? Some sort of timeout loop? Ideally I would really like to keep it all contained within this particular script, rather than having to add any extra stuff to the page that is being opened.
First of all, I believe you are supposed to affect the src property of iframes, not location. Second of all, hook the iframe's load event to perform your changes:
var myIframe = document.getElementById('righttop');
myIframe.addEventListener("load", function() {
this.contentWindow.document.notesform.ID_client.value = Client;
});
myIframe.src = 'timesheet_notes.php';
Again, this is all presuming you mean iframe, not framesets.
I guess you can pretty easily do this with jQuery... jQuery Home
Just hook the page to the jQuery $ function ()... e.g.
$(document).ready(function() {
$('iframe').load(function() {
// write your code here....
});
});
Have a quick look at the file uploader example here:
Using iframes for multiple file uploads...
iFrame could have dynamically loaded elements and the best option to work with them is to use recursion:
$('iframe').ready(function() {
var triggerMeAgainIfNeeded = function() {
setTimeout(function() {
var neededElm = $('.someElementThatLoadedAfterIframe');
if (neededElm.length > 0) {
// do your job
} else {
triggerMeAgainIfNeeded();
}
}, 10);
}
});
try this one...
$('iframe').each(function() {
$(this).ready(function() {
$('#result').html("ready");
});
});

Categories