Hello i'm finished an app for android using phonegap, right now i'm trying to change the code for a webapp ( the app is simply a notes save ), But i have a problem when change pages, after a edit a note the app goes back to the index page and when you click on a note for view a single note, the apps goes again of the index page ( this happens once, if you click again , works fine)
DEMO
notesapp
THis is part of js code
editNote: function(e){
var noteId = $("#id-note").attr("value");
var newText = $.trim($("#textarea-edit").val());
var storage = window.localStorage.getItem("notes");
storage = JSON.parse(storage);
var newStorage = [];
for( obj in storage ){
if(noteId == storage[obj].id){
newStorage.push({
id: storage[obj].id,
text: newText,
created: storage[obj].created
});
}else{
newStorage.push(storage[obj])
}
}
window.localStorage.setItem("notes", JSON.stringify(newStorage));
notes.showNotes();
$.mobile.changePage($('#index'));
}
$(document).bind("pagebeforechange", function(e, data){
var u = $.mobile.path.parseUrl( data.toPage )
if(u.hash){
var page = u.hash.split("?")[0],
idNote = u.hash.split("=")[1],
storage = window.localStorage.getItem("notes"),
singleText
;
storage = JSON.parse(storage);
// GET CURRENT NOTE TEXT
for( obj in storage ){
if(idNote == storage[obj].id){
singleText = storage[obj].text;
}
}
// SET ID-NOTE TO A INPUT HIDE FOR LATER RETRIEVE
$("#id-note").attr("value", idNote)
if(page == "#single"){
if(idNote){
console.log("show single page")
$("#single-note").html(singleText);
$("#editnote-button").attr("href","#editnote?id=" + idNote);
}
}else if(page == "#editnote"){
console.log("Show edit")
$("#textarea-edit").val(singleText);
}
}
});
Your problem lies in executing notes.init() whenever a page is initiated pageinit. As per your code, notes.init() adds multiple click listener to the buttons below.
$("#save-note").on("click", notes.saveNote);
$("#delete-note").on("click", notes.deleteNote);
$("#edit-note-button").on("click", notes.editNote);
To solve the problem, either bind pageinit to #index page. This way notes.init() will run once only. Or remove old click binding and re-bind it to same buttons.
$("#save-note").off("click").on("click", notes.saveNote);
$("#delete-note").off("click").on("click", notes.deleteNote);
$("#edit-note-button").off("click").on("click", notes.editNote);
Or run pageinit one time only.
$(document).one("pageinit", function () {
notes.init();
});
Related
Here's the problem. I'm making a callback to the server that receives an MVC partial page. It's been working great, it calls the success function and all that. However, I'm calling a function after which iterates through specific elements:
$(".tool-fields.in div.collapse, .common-fields div.collapse").each(...)
Inside this, I'm checking for a specific attribute (custom one using data-) which is also working great; however; the iterator never finishes. No error messages are given, the program doesn't hold up. It just quits.
Here's the function with the iterator
function HideShow() {
$(".tool-fields.in div.collapse, .common-fields div.collapse").each(function () {
if (IsDataYesNoHide(this)) {
$(this).collapse("show");
}
else
$(this).collapse("hide");
});
alert("test");
}
Here's the function called in that, "IsDataYesNoHide":
function IsDataYesNoHide(element) {
var $element = $(element);
var datayesnohide = $element.attr("data-yes-no-hide");
if (datayesnohide !== undefined) {
var array = datayesnohide.split(";");
var returnAnswer = true;
for (var i in array) {
var answer = array[i].split("=")[1];
returnAnswer = returnAnswer && (answer.toLowerCase() === "true");
}
return returnAnswer;
}
else {
return false;
}
}
This is the way the attribute appears
data-yes-no-hide="pKanban_Val=true;pTwoBoxSystem_Val=true;"
EDIT: Per request, here is the jquery $.post
$.post(path + conPath + '/GrabDetails', $.param({ data: dataArr }, true), function (data) {
ToggleLoader(false); //Page load finished so the spinner should stop
if (data !== "") { //if we got anything back of if there wasn't a ghost record
$container.find(".container").first().append(data); //add the content
var $changes = $("#Changes"); //grab the changes
var $details = $("#details"); //grab the current
SplitPage($container, $details, $changes); //Just CSS changes
MoveApproveReject($changes); //Moves buttons to the left of the screen
MarkAsDifferent($changes, $details) //Adds the data- attribute and colors differences
}
else {
$(".Details .modal-content").removeClass("extra-wide"); //Normal page
$(".Details input[type=radio]").each(function () {
CheckOptionalFields(this);
});
}
HideShow(); //Hide or show fields by business logic
});
For a while, I thought the jquery collapse was breaking, but putting the simple alert('test') showed me what was happening. It just was never finishing.
Are there specific lengths of time a callback function can be called from a jquery postback? I'm loading everything in modal views which would indicate "oh maybe jquery is included twice", but I've already had that problem for other things and have made sure that it only ever includes once. As in the include is only once in the entire app and the layout is only applied to the main page.
I'm open to any possibilities.
Thanks!
~Brandon
Found the problem. I had a variable that was sometimes being set as undefined cause it to silently crash. I have no idea why there was no error message.
First Question here, too! Yay! Just moved this from AskUbuntu.
I am just about to finish a little private project for gaining some experience where i try to change the app layout so it works as a normal website (on Jimdo, so it was quite of a challenge first) without much JavaScript required but is fully functional on mobile view.
Since Jimdo serves naturally only the actual site, I had to implement an
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
redirect into the __doSelectTab() function in tabs.js . (In js I took the values from the jimdo menu string to build the TABS menu with this link attribute)
Now everything works fine exept at page load the first tab is selected. I got it to set the .active and .inactive classes right easily, but it is not shifted to the left.
So my next idea is to let it initialize as always and then send a command to change to the current tab.
Do you have any idea how to manage this? I couldn't because of the this.thisandthat element I apparently don't really understand...
Most of you answering have the toolkit and the whole code, but I am listing the select function part of the tabs.js:
__doSelectTab: function(tabElement, forcedSelection) {
if ( ! tabElement)
return;
if (tabElement.getAttribute("data-role") !== 'tabitem')
return;
if (forcedSelection ||
(Array.prototype.slice.call(tabElement.classList)).indexOf('inactive') > -1) {
window.clearTimeout(t2);
activeTab = this._tabs.querySelector('[data-role="tabitem"].active');
offsetX = this.offsetLeft;
this._tabs.style['-webkit-transition-duration'] = '.3s';
this._tabs.style.webkitTransform = 'translate3d(-' + offsetX + 'px,0,0)';
this.__updateActiveTab(tabElement, activeTab);
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (e) {
e.classList.remove('inactive');
});
var targetPageId = tabElement.getAttribute('data-page');
this.activate(targetPageId);
this.__dispatchTabChangedEvent(targetPageId);
} else {
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (el) {
el.classList.toggle('inactive');
});
var self = this;
t2 = window.setTimeout(function () {
var nonActiveTabs = self._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)');
[].forEach.call(nonActiveTabs, function (el) {
el.classList.toggle('inactive');
});
}, 3000);
}
},
...and my app.js hasn't anything special:
var UI = new UbuntuUI();
document.addEventListener('deviceready', function() { console.log('device ready') }, true);
$(document).ready(function () {
recreate_jimdo_nav();
UI.init();
});
So meanwhile found a simple workaround, however I'd still like to know if there is another way. Eventually I noticed the __doSelectTab() function is the one that executes the click, so it does nothing but to show the other tab names when they are hidden first. so I added the global value
var jnavinitialized = false;
at the beginning of the tabs.js and run
var t = this;
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 0);
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 1);
setTimeout(function(){jnavinitialized = true;}, 10);
at the top of the __setupInitialTabVisibility() function. Then I changed the location.href command to
if (activeTab.getAttribute('jimdo-target') != null && jnavinitialized)
location.href = activeTab.getAttribute('jimdo-target');
And it works. But originally I searched for a way to change the tab on command, not to run the command for selecting twice. So if you know a better or cleaner way, you are welcome!
Here is my HTML
$html .= " <td><div class='edit_course' data-id='{$id}' data-type='_title' contenteditable='true'>{$obj->title}</div></td>";
Here is my jQuery:
var selector = 'div[contenteditable="true"]';
// initialize the "save" function
$(selector).focus(function(e) {
content_holder = $(this);
content = content_holder.html();
var id = $(this).data('id');
var type = $(this).data('type');
alert( id + type)
// one click outside the editable area saves the content
$('body').one('click', function(e) {
// but not if the content didn't change
if ($(e.target).is(selector) || content == content_holder.html()) {
return;
}
// Edited out AJAX call
});
});
The problem is, when I click on the div, the alert below triggers. When I click outside of the div (after the edit has been made), nothing happens. Can anyone see what is happening?
First click let's user edit content in div. The first click outside, should make ajax call to save.
EDIT: From recommendation below.
Here is new code this works perfectly except it calls the DB every time, all I need is a check to do that only if data is different and I think I got it from there.
Edit2: Final Code
var original_value = '';
$(".edit_course").focus(function(e) {
original_value = $(this).html();
});
// initialize the "save" function
$(".edit_course").blur(function(e) {
var content = $(this).html();
var id = $(this).data('id');
var type = $(this).data('type');
if (content !== original_value) {
// Ajax edited out
}
});
You're not using one() correctly. What you should do is run the AJAX when focus is taken away from the div. Using blur() would probably be your best bet here.
$('body').blur(function(e) {
// your code here...
});
My goal is to store the total amount of clicks on links in a certain page into a variable and recall that variable when the user exits the page. Would this be a correct way of doing it?
window.onunload = function(){
alert("Total Links Clicked:" + clicks(););
}
var clicks = function(){
var clickArray = [];
var getLinks = document.getElementsByTagName(A);
var clickValue = getLinks.onclick = function() {
clickArray.push("1");
}
var totalClicks = clickArray.length;
return totalClicks;
}
Your code won't work for several reasons:
You bind the click handler in clicks() function and don't call clicks() until the page is unloaded, at which point it is too late to handle any clicks. You need to bind the click handler when the page loads.
You can't set .onclick on a list of elements, which is what your getLinks variable is given it was set to the result of getElementsByTagName() (get elements not get element).
You pass an undeclared variable A to getElementsByTagName(); you should pass the string "a".
You have a semicolon inside the alert()'s closing ), which is a syntax error.
You could try something like this:
window.onload = function() {
var clicks = 0;
window.onunload = function(){
alert("Total Links Clicked:" + clicks);
}
function clicked() {
clicks++;
}
var getLinks = document.getElementsByTagName("a");
for (var i = 0; i < getLinks.length; i++)
getLinks[i].onclick = clicked;
};
Note that the browser may block an alert() during an unload event, but if you use console.log() instead you can see that clicks had the right value.
Note also that of course a click on a link to another page will cause an unload, so the click count will only be more than 1 if you have links within the current page.
Demo: http://jsfiddle.net/A3bkT/1/
You can use sessionStorage or localStorage for that.
if(typeof(Storage)!=="undefined")
{
// store the clicks here
sessionStorage.numClicks = value;
}
and read more on these two here : http://www.w3schools.com/html/html5_webstorage.asp
Bind a global event listener and just store the count with sessionStorage:
var clicks = 0;
document.addEventListener('click', function(event) {
if (event.target.nodeName == 'A') {
window.sessionStorage.setItem('clicks', ++clicks);
}
}, false);
I have a <select> tag. On changing the selected item, some <div>s are updated using AJAX via the functions: update_div1, update_div2, update_div3. The code managing this operation is below and working well:
$('select.select-x').change(function(e) {
e.preventDefault();
var value = $('select.select-x option:selected').val();
var text = $('option:selected').text();
update_div1(value);
update_div2(value);
update_div3(value);
manage_history(value,text);
return false;
});
The problem is in the last function manage_history which is responsable of managing browser history. In this function I am using history.js to push browser states in history stack. As I know after reading many articles on SO about history.js, the actions of back and forward buttons should be inclueded in History.Adapter.bind(). The problem is that the back-forward buttons of the browser are having weird behaviour: They execute the functions inside History.Adapter.bind() many times, exaclty the number of times I already had an onChange event triggerd via <select>.
The code of manage_history is:
function manage_history(str,str2)
{
var History = window.History;
if ( !History.enabled ) { return false; }
var path = 'http://localhost/enc/?p='+str;
History.pushState({myid:str},str2,path);
History.Adapter.bind(window,'statechange',function() {
var State = History.getState();
update_div1(State.data.myid); fter
update_div2(State.data.myid);
update_div3(State.data.myid);
});
}
I hope I was clear. Your help is appreciated.
The whole Solution after theBrain contribution:
$('select.select-x').change(function(e) {
e.preventDefault();
var value = $('select.select-x option:selected').val();
var text = $('option:selected').text();
manage_history(value,text);
return false;
});
History.Adapter.bind(window,'statechange',function() { // Note: Using statechange instead of popstate
var State = History.getState();
update_div1(value);
update_div2(value);
update_div3(value);
});
function manage_history(str,str2)
{
var History = window.History;
if ( !History.enabled ) { return false; }
var path = 'http://localhost/enc/?p='+str;
History.pushState({myid:str},str2,path);
update_div1(State.data.myid);
update_div2(State.data.myid);
update_div3(State.data.myid);
}
move the History.Adapter.bind away from the manage_history function. You rebind it every time you call the manage_history function.