Nested Javascript function - javascript

I have two javascript functions for pagination and truncate as follow:
<script type="text/javascript" src="//path/js/jquery.quick.pagination.min.js"></script>
$("#post_list").quickPagination({
pagerLocation:"both",
pageSize:"3"
});
<script type="text/javascript" language="javascript" src="//path/js/jquery.dotdotdot.js"></script>
$(".post_detail").dotdotdot({
after: 'a.more',
callback : function( isTruncated, orgContent ) {
if (!isTruncated) {
$('.more',this).remove()
}
},
});
Each runs fine onLoad. However, once the pagination function is fired, the truncate function does not run again.
Please see my jsfiddle and click page 2 to see the problem.
jsfiddle: http://jsfiddle.net/wr2ezv4f/1/
EDITED:
I managed to include the truncate function by adding it directly to the jquery.quick.pagination.min.js file (Please see the comment inside the js as folow (AND is working well):
(function($) {
"use strict";
$.fn.quickPagination = function(options) {
var defaults = {
pageSize: 10,
currentPage: 1,
holder: null,
pagerLocation: "after",
transitionSpeed: null
};
options = $.extend(defaults, options);
return this.each(function() {
var selector = $(this);
var pageCounter = 1;
if ($(".simplePagerContainer").length < 1) selector.wrap("<div class='simplePagerContainer'></div>");
selector.parents(".simplePagerContainer").find("ul.simplePagerNav").remove();
selector.children().removeClass(function(index, css) {
return (css.match(/simplePagerPage([0-9]+)?/ig) || []).join(' ');
}).filter(":visible").each(function(i) {
if (i < pageCounter * options.pageSize && i >= (pageCounter - 1) * options.pageSize) {
$(this).addClass("simplePagerPage" + pageCounter);
} else {
$(this).addClass("simplePagerPage" + (pageCounter + 1));
pageCounter++;
}
});
selector.children().hide();
selector.children(".simplePagerPage" + options.currentPage).show();
if (pageCounter <= 1) {
return;
}
var pageNav = "<ul class='simplePagerNav'>";
for (var i = 1; i <= pageCounter; i++) {
if (i == options.currentPage) {
pageNav += "<li class='page currentPage simplePageNav" + i + "'><a rel='" + i + "' href='#'>" + i + "</a></li>";
} else {
pageNav += "<li class='page simplePageNav" + i + "'><a rel='" + i + "' href='#'>" + i + "</a></li>";
}
}
pageNav += "</ul>";
if (!options.holder) {
switch (options.pagerLocation) {
case "before":
selector.before(pageNav);
break;
case "both":
selector.before(pageNav);
selector.after(pageNav);
break;
default:
selector.after(pageNav);
}
} else {
$(options.holder).append(pageNav);
}
selector.parent().find(".simplePagerNav a").click(function(e) {
e.preventDefault();
var clickedLink = $(this).attr("rel");
options.currentPage = clickedLink;
var container = options.holder ? options.holder : ".simplePagerContainer";
$(this).parents(container).find("li.currentPage").removeClass("currentPage");
$(this).parents(container).find("a[rel='" + clickedLink + "']").parent("li").addClass("currentPage");
selector.children().hide();
if (options.transitionSpeed) {
selector.find(".simplePagerPage" + clickedLink).fadeIn(options.transitionSpeed);
// ** I managed to include the truncate function here **//
$(".post_title").dotdotdot();
$(".post_detail").dotdotdot({
after: 'a.more',
callback : function( isTruncated, orgContent ) {
if (!isTruncated) {
$('.more',this).remove()
}
},
});
} else {
selector.find(".simplePagerPage" + clickedLink).show();
//** and to include the truncate function here **//
$(".post_title").dotdotdot();
$(".post_detail").dotdotdot({
after: 'a.more',
callback : function( isTruncated, orgContent ) {
if (!isTruncated) {
$('.more',this).remove()
}
},
});
}
return false;
});
});
};
})(jQuery);
My question now is, how can I modify this js file so that I can include this function outside the js file instead:
Something like:
$("#post_list").quickPagination({
pagerLocation:"both",
pageSize:"3"
// ** optional function I want to include here **/
});

You can write both function in a common function like this
$(function()
{
$("#post_list").quickPagination({
pagerLocation:"both",
pageSize:"3"
});
$(".post_title").dotdotdot();
$(".post_detail").dotdotdot({
after: 'a.more',
callback : function( isTruncated, orgContent ) {
if (!isTruncated) {
$('.more',this).remove()
}
},
});
});

Related

Loading two similar scripts twice dosn't work

i have this javascript that I called cookiebar.js, it shows a sticky bar message for cookies, (source code)
(function (context) {
"use strict";
var win = context,
doc = win.document;
var global_instance_name = "cbinstance";
function contentLoaded(win, fn) {
var done = false,
top = true,
doc = win.document,
root = doc.documentElement,
add = doc.addEventListener ? "addEventListener" : "attachEvent",
rem = doc.addEventListener ? "removeEventListener" : "detachEvent",
pre = doc.addEventListener ? "" : "on",
init = function (e) {
if (e.type == "readystatechange" && doc.readyState != "complete") return;
(e.type == "load" ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
},
poll = function () {
try {
root.doScroll("left");
} catch (e) {
setTimeout(poll, 50);
return;
}
init("poll");
};
if (doc.readyState == "complete") fn.call(win, "lazy");
else {
if (doc.createEventObject && root.doScroll) {
try {
top = !win.frameElement;
} catch (e) {}
if (top) poll();
}
doc[add](pre + "DOMContentLoaded", init, false);
doc[add](pre + "readystatechange", init, false);
win[add](pre + "load", init, false);
}
}
var Cookies = {
get: function (key) {
return decodeURIComponent(doc.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
set: function (key, val, end, path, domain, secure) {
if (!key || /^(?:expires|max\-age|path|domain|secure)$/i.test(key)) {
return false;
}
var expires = "";
if (end) {
switch (end.constructor) {
case Number:
expires = end === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + end;
break;
case String:
expires = "; expires=" + end;
break;
case Date:
expires = "; expires=" + end.toUTCString();
break;
}
}
doc.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(val) + expires + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "") + (secure ? "; secure" : "");
return true;
},
has: function (key) {
return new RegExp("(?:^|;\\s*)" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=").test(doc.cookie);
},
remove: function (key, path, domain) {
if (!key || !this.has(key)) {
return false;
}
doc.cookie = encodeURIComponent(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "");
return true;
},
};
var Utils = {
merge: function () {
var obj = {},
i = 0,
al = arguments.length,
key;
if (0 === al) {
return obj;
}
for (; i < al; i++) {
for (key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
},
str2bool: function (str) {
str = "" + str;
switch (str.toLowerCase()) {
case "false":
case "no":
case "0":
case "":
return false;
default:
return true;
}
},
fade_in: function (el) {
if (el.style.opacity < 1) {
el.style.opacity = (parseFloat(el.style.opacity) + 0.05).toFixed(2);
win.setTimeout(function () {
Utils.fade_in(el);
}, 50);
}
},
get_data_attribs: function (script) {
var data = {};
if (Object.prototype.hasOwnProperty.call(script, "dataset")) {
data = script.dataset;
} else {
var attribs = script.attributes;
var key;
for (key in attribs) {
if (Object.prototype.hasOwnProperty.call(attribs, key)) {
var attr = attribs[key];
if (/^data-/.test(attr.name)) {
var camelized = Utils.camelize(attr.name.substr(5));
data[camelized] = attr.value;
}
}
}
}
return data;
},
normalize_keys: function (options_object) {
var camelized = {};
for (var key in options_object) {
if (Object.prototype.hasOwnProperty.call(options_object, key)) {
var camelized_key = Utils.camelize(key);
camelized[camelized_key] = options_object[camelized_key] ? options_object[camelized_key] : options_object[key];
}
}
return camelized;
},
camelize: function (str) {
var separator = "-",
match = str.indexOf(separator);
while (match != -1) {
var last = match === str.length - 1,
next = last ? "" : str[match + 1],
upnext = next.toUpperCase(),
sep_substr = last ? separator : separator + next;
str = str.replace(sep_substr, upnext);
match = str.indexOf(separator);
}
return str;
},
find_script_by_id: function (id) {
var scripts = doc.getElementsByTagName("script");
for (var i = 0, l = scripts.length; i < l; i++) {
if (id === scripts[i].id) {
return scripts[i];
}
}
return null;
},
};
var script_el_invoker = Utils.find_script_by_id("cookiebanner");
var Cookiebanner = (context.Cookiebanner = function (opts) {
this.init(opts);
});
Cookiebanner.prototype = {
cookiejar: Cookies,
init: function (opts) {
this.inserted = false;
this.closed = false;
this.test_mode = false;
var default_text = "This site uses cookies.";
var default_link = "Detail";
this.default_options = {
cookie: "cookiebanner-accepted",
closeText: "✖",
cookiePath: "/",
debug: false,
expires: Infinity,
zindex: 255,
mask: false,
maskOpacity: 0.5,
maskBackground: "#000",
height: "auto",
minHeight: "21px",
bg: "#000",
fg: "#ddd",
link: "#aaa",
position: "bottom",
message: default_text,
linkmsg: default_link,
moreinfo: "http://www.examplesite123.com/cookie-policy/",
effect: null,
fontSize: "14px",
fontFamily: "arial, sans-serif",
instance: global_instance_name,
textAlign: "center",
acceptOnScroll: true,
};
this.options = this.default_options;
this.script_el = script_el_invoker;
if (this.script_el) {
var data_options = Utils.get_data_attribs(this.script_el);
this.options = Utils.merge(this.options, data_options);
}
if (opts) {
opts = Utils.normalize_keys(opts);
this.options = Utils.merge(this.options, opts);
}
global_instance_name = this.options.instance;
this.options.zindex = parseInt(this.options.zindex, 10);
this.options.mask = Utils.str2bool(this.options.mask);
if ("string" === typeof this.options.expires) {
if ("function" === typeof context[this.options.expires]) {
this.options.expires = context[this.options.expires];
}
}
if ("function" === typeof this.options.expires) {
this.options.expires = this.options.expires();
}
if (this.script_el) {
this.run();
}
},
log: function () {
if ("undefined" !== typeof console) {
console.log.apply(console, arguments);
}
},
run: function () {
if (!this.agreed()) {
var self = this;
contentLoaded(win, function () {
self.insert();
});
}
},
build_viewport_mask: function () {
var mask = null;
if (true === this.options.mask) {
var mask_opacity = this.options.maskOpacity;
var bg = this.options.maskBackground;
var mask_markup =
'<div id="cookiebanner-mask" style="' +
"position:fixed;top:0;left:0;width:100%;height:100%;" +
"background:" +
bg +
";zoom:1;filter:alpha(opacity=" +
mask_opacity * 100 +
");opacity:" +
mask_opacity +
";" +
"z-index:" +
this.options.zindex +
';"></div>';
var el = doc.createElement("div");
el.innerHTML = mask_markup;
mask = el.firstChild;
}
return mask;
},
agree: function () {
this.cookiejar.set(this.options.cookie, 1, this.options.expires, this.options.cookiePath);
return true;
},
agreed: function () {
return this.cookiejar.has(this.options.cookie);
},
close: function () {
if (this.inserted) {
if (!this.closed) {
if (this.element) {
this.element.parentNode.removeChild(this.element);
}
if (this.element_mask) {
this.element_mask.parentNode.removeChild(this.element_mask);
}
this.closed = true;
}
}
return this.closed;
},
agree_and_close: function () {
this.agree();
return this.close();
},
cleanup: function () {
this.close();
return this.unload();
},
unload: function () {
if (this.script_el) {
this.script_el.parentNode.removeChild(this.script_el);
}
context[global_instance_name] = undefined;
return true;
},
insert: function () {
this.element_mask = this.build_viewport_mask();
var zidx = this.options.zindex;
if (this.element_mask) {
zidx += 1;
}
var el = doc.createElement("div");
el.className = "cookiebanner";
el.style.position = "fixed";
el.style.left = 0;
el.style.right = 0;
el.style.height = this.options.height;
el.style.minHeight = this.options.minHeight;
el.style.zIndex = zidx;
el.style.background = this.options.bg;
el.style.color = this.options.fg;
el.style.lineHeight = el.style.minHeight;
el.style.padding = "5px 16px";
el.style.fontFamily = this.options.fontFamily;
el.style.fontSize = this.options.fontSize;
el.style.textAlign = this.options.textAlign;
if ("top" === this.options.position) {
el.style.top = 0;
} else {
el.style.bottom = 0;
}
el.innerHTML = '<div class="cookiebanner-close" style="float:right;padding-left:5px;">' + this.options.closeText + "</div>" + "<span>" + this.options.message + " <a>" + this.options.linkmsg + "</a></span>";
this.element = el;
var el_a = el.getElementsByTagName("a")[0];
el_a.href = this.options.moreinfo;
el_a.target = "_blank";
el_a.style.textDecoration = "none";
el_a.style.color = this.options.link;
var el_x = el.getElementsByTagName("div")[0];
el_x.style.cursor = "pointer";
function on(el, ev, fn) {
var add = el.addEventListener ? "addEventListener" : "attachEvent",
pre = el.addEventListener ? "" : "on";
el[add](pre + ev, fn, false);
}
var self = this;
on(el_x, "click", function () {
self.agree_and_close();
});
if (this.element_mask) {
on(this.element_mask, "click", function () {
self.agree_and_close();
});
doc.body.appendChild(this.element_mask);
}
if (this.options.acceptOnScroll) {
on(window, "scroll", function () {
self.agree_and_close();
});
}
doc.body.appendChild(this.element);
this.inserted = true;
if ("fade" === this.options.effect) {
this.element.style.opacity = 0;
Utils.fade_in(this.element);
} else {
this.element.style.opacity = 1;
}
},
};
if (script_el_invoker) {
if (!context[global_instance_name]) {
context[global_instance_name] = new Cookiebanner();
}
}
})(window);
I load it in this way in functions.php in Wordpress:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
It works fine.
Now i duplicate the same javascript code and i called it stickybar.js. I add some modifications, also change class with name "stickybar":
The code of the stickybar.js is here (i pasted it in jsfiddle because there is too much text for stackoverflow)
Then i show this second bar (stickybar.js) only on mobile device and after 8 second with this CSS:
.stickybar { display: none; }
#media only screen and (max-device-width:480px) {
.stickybar {
display: block;
animation: cssAnimation 0s 8s forwards;
visibility: hidden;
}
#keyframes cssAnimation {
to { visibility: visible; }
}
}
I load it in Wordpress with this code in functions.php:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
It works fine.
If i load one by one of this codes, they work fine.
The problem is that when i load the two scripts together in this way in functions.php, only the first works:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
How can i load the two scripts together?
The comment thread on this question is semantically correct, you can only have one instance of each html id attribute, they must be unique, and your find_script_by_id methods are both searching for the same thing.
However, you're doing what's generally called "baking in" the scripts into your header which is at best, a faux pas, at least as far as WordPress is concerned. Properly Enqueueing Scripts (and styles) is very easy in WordPress, and your future self, web clients, and other people who look at your code will thank you for doing it.
It's not unlike how you're "baking in" the scripts now:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
But with a few things changed:
function enqueue_my_scripts(){
wp_enqueue_script( 'cookie-bar', 'https://www.examplesite123.com/cookiebar.js', array(), '1.0', true );
wp_enqueue_script( 'sticky-bar', 'https://www.examplesite123.com/stickybar.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );
Namely, it uses the wp_enqueue_script() function on the wp_enqueue_scripts hook. This lets you defer the script to the footer, load in the header, add version numbers to prevent caching issues, add dependencies, allows you to dynamically add/remove them programatically,gives them unique ID's based on the handle, and much more. (You do still need to update your find_script_by_id functions to use these new handles instead cookie-bar, sticky-bar, change the global_instance_name, etc. (more on that in a second)
With that said, if the .js files are on your server, you'll want to use site_url(), plugins_url(), get_stylesheet_directory_uri(), or similar functions to grab the URL of the file instead of typing it out. If you're using a remote resource, don't worry about it, but if they're on you're site, you should swap out the baked in version for that so you don't have issues if you ever move your site, and it allows you easier methods to edit the version to prevent caching problems if you change them.
Back to your variables, you may also want to replace your find_script_by_id type functions with document.currentScript instead, to allow them to be more abstract and not rely on typo/duplicate prone element IDs, and instead reference the currently running <script> tag.

JavaScript jQuery.post to get data from .php file in Firefox Extension

I'm trying to make a Firefox extension based on iNettuts widget interface:
Source 1
Source 2
My goal is to get the widget's content from the widgets_rpc.php file:
<?php
header("Cache-Control: no-cache");
header("Pragma: nocache");
$id=$_REQUEST["id"];
echo "<p>This is the content for <b>$id</b></p>";
switch ($id) {
case "widget1":
echo "<p>This is the content for widget #1</p>";
break;
case "widget2":
echo "<p>This is the content for widget #2</p>";
break;
case "widget3":
echo "<p>This is the content for widget #3</p>";
break;
default: echo "<p>OK</p>";
}
?>
Source JS:
/*
* Script from NETTUTS.com [modified by Mario Jimenez] V.3 (ENHANCED, WITH DATABASE, ADD WIDGETS FEATURE AND COOKIES OPTION!!!)
* #requires jQuery($), jQuery UI & sortable/draggable UI modules
*/
var ios = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var cookieUri = ios.newURI("chrome://mystartpage/content/index.html", null, null);
var cookieSvc = Components.classes["#mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);
var cookieVal = " ";
var iNettuts = {
jQuery : $,
settings : {
columns : '.column',
widgetSelector: '.widget',
handleSelector: '.widget-head',
contentSelector: '.widget-content',
saveToDB: false,
cookieName: '',
widgetDefault : {
movable: true,
removable: true,
collapsible: true,
editable: true,
colorClasses: ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green'],
content: "<div align='center'><img src='/skin/img/load.gif' border='0' /></div>"
},
widgetIndividual : {
widget1 : {
movable: true,
removable: true,
collapsible: true,
editable: true,
mycontent: "asd"
}
}
},
init : function () {
this.attachStylesheet('/skin/inettuts.js.css');
$('body').css({background:'#000'});
$(this.settings.columns).css({visibility:'visible'});
this.sortWidgets();
//this.addWidgetControls();
//this.makeSortable();
},
initWidget : function (opt) {
if (!opt.content) opt.content=iNettuts.settings.widgetDefault.content;
return '<li id="'+opt.id+'" class="new widget '+opt.color+'"><div class="widget-head"><h3>'+opt.title+'</h3></div><div class="widget-content">'+opt.content+'</div></li>';
},
/*loadWidget : function(id) {
$.post("widgets_rpc.php", {"id":id},
function(data){
$("#"+id+" "+iNettuts.settings.contentSelector).html(data);
});
},*/
loadWidget : function(id) {
$.post("widgets_rpc.php", {"id":id},
function(data){
var thisWidgetSettings = iNettuts.getWidgetSettings(id);
if (thisWidgetSettings.mycontent) data+=thisWidgetSettings.mycontent;
$("#"+id+" "+iNettuts.settings.contentSelector).html(data);
});
},
addWidget : function (where, opt) {
$("li").removeClass("new");
var selectorOld = iNettuts.settings.widgetSelector;
iNettuts.settings.widgetSelector = '.new';
$(where).append(iNettuts.initWidget(opt));
iNettuts.addWidgetControls();
iNettuts.settings.widgetSelector = selectorOld;
iNettuts.makeSortable();
iNettuts.savePreferences();
iNettuts.loadWidget(opt.id);
},
getWidgetSettings : function (id) {
var $ = this.jQuery,
settings = this.settings;
return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
},
addWidgetControls : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings;
$(settings.widgetSelector, $(settings.columns)).each(function () {
var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);
if (thisWidgetSettings.removable) {
$('CLOSE').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function () {
if(confirm('This widget will be removed, ok?')) {
$(this).parents(settings.widgetSelector).animate({
opacity: 0
},function () {
$(this).wrap('<div/>').parent().slideUp(function () {
$(this).remove();
iNettuts.savePreferences();
});
});
}
return false;
}).appendTo($(settings.handleSelector, this));
}
if (thisWidgetSettings.editable) {
$('EDIT').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).toggle(function () {
$(this).css({backgroundPosition: '-66px 0', width: '55px'})
.parents(settings.widgetSelector)
.find('.edit-box').show().find('input').focus();
return false;
},function () {
$(this).css({backgroundPosition: '', width: '24px'})
.parents(settings.widgetSelector)
.find('.edit-box').hide();
return false;
}).appendTo($(settings.handleSelector,this));
$('<div class="edit-box" style="display:none;"/>')
.append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')
.append((function(){
var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';
$(thisWidgetSettings.colorClasses).each(function () {
colorList += '<li class="' + this + '"/>';
});
return colorList + '</ul>';
})())
.append('</ul>')
.insertAfter($(settings.handleSelector,this));
}
if (thisWidgetSettings.collapsible) {
$('COLLAPSE').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function(){
$(this).parents(settings.widgetSelector).toggleClass('collapsed');
/* Save prefs to cookie: */
iNettuts.savePreferences();
return false;
}).prependTo($(settings.handleSelector,this));
}
});
$('.edit-box').each(function () {
$('input',this).keyup(function () {
$(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() );
iNettuts.savePreferences();
});
$('ul.colors li',this).click(function () {
var colorStylePattern = /\bcolor-[\w]{1,}\b/,
thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
if (thisWidgetColorClass) {
$(this).parents(settings.widgetSelector)
.removeClass(thisWidgetColorClass[0])
.addClass($(this).attr('class').match(colorStylePattern)[0]);
/* Save prefs to cookie: */
iNettuts.savePreferences();
}
return false;
});
});
},
attachStylesheet : function (href) {
var $ = this.jQuery;
return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
},
makeSortable : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings,
$sortableItems = (function () {
var notSortable = '';
$(settings.widgetSelector,$(settings.columns)).each(function (i) {
if (!iNettuts.getWidgetSettings(this.id).movable) {
if(!this.id) {
this.id = 'widget-no-id-' + i;
}
notSortable += '#' + this.id + ',';
}
});
if (notSortable=='')
return $("> li", settings.columns);
else
return $('> li:not(' + notSortable + ')', settings.columns);
})();
$sortableItems.find(settings.handleSelector).css({
cursor: 'move'
}).mousedown(function (e) {
$sortableItems.css({width:''});
$(this).parent().css({
width: $(this).parent().width() + 'px'
});
}).mouseup(function () {
if(!$(this).parent().hasClass('dragging')) {
$(this).parent().css({width:''});
} else {
$(settings.columns).sortable('disable');
}
});
$(settings.columns).sortable('destroy');
$(settings.columns).sortable({
items: $sortableItems,
connectWith: $(settings.columns),
handle: settings.handleSelector,
placeholder: 'widget-placeholder',
forcePlaceholderSize: true,
revert: 300,
delay: 100,
opacity: 0.8,
containment: 'document',
start: function (e,ui) {
$(ui.helper).addClass('dragging');
},
stop: function (e,ui) {
$(ui.item).css({width:''}).removeClass('dragging');
$(settings.columns).sortable('enable');
iNettuts.savePreferences();
}
});
},
savePreferences : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings,
cookieString = '';
/* Assemble the cookie string */
$(settings.columns).each(function(i){
cookieString += (i===0) ? '' : '|';
$(settings.widgetSelector,this).each(function(i){
cookieString += (i===0) ? '' : '&';
/* ID of widget: */
cookieString += $(this).attr('id') + ',';
/* Color of widget (color classes) */
cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';
/* Title of widget (replaced used characters) */
cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ',';
/* Collapsed/not collapsed widget? : */
cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed' : 'not-collapsed';
});
});
if(settings.saveToDB) {
/* AJAX call to store string on database */
$.post("iNettuts_rpc.php","value="+cookieString);
} else {
cookieSvc.setCookieString(cookieUri, null, "" + cookieString + ";expires=Thu, 31 Dec 2099 00:00:00 GMT", null);
}
},
sortWidgets : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings;
if (settings.saveToDB) {
$.post("iNettuts_rpc.php", "", this.processsSavedData);
} else {
var cookie = cookieSvc.getCookieString(cookieUri, null);
this.processsSavedData(cookie);
}
//$('body').css({background:'#000'});
//$(settings.columns).css({visibility:'visible'});
return;
},
processsSavedData : function (cookie) {
if (!cookie) {
$('body').css({background:'#000'});
$(iNettuts.settings.columns).css({visibility:'visible'});
iNettuts.addWidgetControls();
iNettuts.makeSortable();
return;
}
/* For each column */
$(iNettuts.settings.columns).each(function(i){
var thisColumn = $(this),
widgetData = cookie.split('|')[i].split('&');
$(widgetData).each(function(){
if(!this.length) {return;}
var thisWidgetData = this.split(','),
opt={
id: thisWidgetData[0],
color: thisWidgetData[1],
title: thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,','),
content: iNettuts.settings.widgetDefault.content
};
$(thisColumn).append(iNettuts.initWidget(opt));
if (thisWidgetData[3]==='collapsed') $('#'+thisWidgetData[0]).addClass('collapsed');
iNettuts.loadWidget(thisWidgetData[0]);
});
});
/* All done, remove loading gif and show columns: */
$('body').css({background:'#000'});
$(iNettuts.settings.columns).css({visibility:'visible'});
iNettuts.addWidgetControls();
iNettuts.makeSortable();
}
};
iNettuts.init();
At this moment the widget shows nothing. Please help.

Bind function in jQuery plugin function

I'm trying to implement an infinite scroll in a div with filtering option, as well, filtering should work when user stops typing in the box.
Html:
<div class="span2" style="margin-top: 50px;">
<input id="Search" class="input-mysize" />
<div id="listNav" style="height: 370px; border: 1px solid; overflow: auto; margin-right: 20px; width: 90%;">
</div>
</div>
JS in Html:
$(function() {
function onSuccess(row, container) {
container.append('<div style="border:1px solid; cursor: hand; cursor: pointer;" >' +
'<table border="0">' +
'<tr>' +
'<td id="Location' + row.Id + '">'+
'<b>Name: </b>' + row.Name + '</br >' + '<b>Address: </b>' + row.Address + '' +
'</td>' +
'<td onclick="locationDetails(' + row.Id + ')"> > </td>' +
'</tr>' +
'</table>' +
'</div>');
var tdId = "Location" + row.Id;
var element = $('#' + tdId);
$(element).click(function() {
google.maps.event.trigger(arrMarkers[row.Id], 'click');
});
};
//...
$('#listNav').empty();
$('#listNav').jScroller("/Dashboard/GetClients", {
numberOfRowsToRetrieve: 7,
onSuccessCallback: onSuccess,
onErrorCallback: function () {
alert("error");
}
});
//...
$('#Search').keyup(function(){
clearTimeout(typingTimer);
if ($('#myInput').val) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
function doneTyping () {
startInt = startInt + 5;
$('#listNav').empty();
$('#listNav').unbind();
$('#listNav').jScroller("/Dashboard/GetClients", {
numberOfRowsToRetrieve: 7,
start : startInt,
locationFilter: $('#Search').val(),
onSuccessCallback: onSuccess,
onErrorCallback: function () {
alert("error");
}
});
};
});
rest of JS (based on jScroller plug in):
(function ($) {
"use strict";
jQuery.fn.jScroller = function (store, parameters) {
var defaults = {
numberOfRowsToRetrieve: 10,
locationFilter: '',
onSuccessCallback: function (row, container) { },
onErrorCallback: function (thrownError) { window.alert('An error occurred while trying to retrive data from store'); },
onTimeOutCallback: function () { },
timeOut: 3 * 1000,
autoIncreaseTimeOut: 1000,
retryOnTimeOut: false,
loadingButtonText: 'Loading...',
loadMoreButtonText: 'Load more',
fullListText: 'There is no more items to show',
extraParams: null
};
var options = jQuery.extend(defaults, parameters);
var list = jQuery(this),
end = false,
loadingByScroll = true;
var ajaxParameters;
if (options.extraParams === null) {
ajaxParameters = {
start: 0,
numberOfRowsToRetrieve: options.numberOfRowsToRetrieve,
locationFilter: options.locationFilter
};
}
else {
ajaxParameters = {
start: 0,
numberOfRowsToRetrieve: options.numberOfRowsToRetrieve,
locationFilter: option.locationFilter,
extraParams: options.extraParams
};
}
list.html('');
function loadItems() {
preLoad();
jQuery.ajax({
url: store,
type: "POST",
data: ajaxParameters,
timeOut: options.timeOut,
success: function (response) {
list.find("#jscroll-loading").remove();
if (response.Success === false) {
options.onErrorCallback(list, response.Message);
return;
}
for (var i = 0; i < response.data.length; i++) {
if (end === false) {
options.onSuccessCallback(response.data[i], list);
}
}
if (loadingByScroll === false) {
if (end === false) {
list.append('<div><a class="jscroll-loadmore">' + options.loadMoreButtonText + '</a></div>');
}
}
ajaxParameters.start = ajaxParameters.start + options.numberOfRowsToRetrieve;
if (ajaxParameters.start >= response.total) {
end = true;
list.find('#jscroll-fulllist').remove();
list.find(".jscroll-loadmore").parent("div").remove();
}
},
error: function (xhr, ajaxOptions, thrownError) {
if (thrownError === 'timeout') {
options.onTimeOutCallback();
if (options.retryOnTimeOut) {
options.timeOut = options.timeOut + (1 * options.autoIncreaseTimeOut);
loadItems();
}
}
else {
options.onErrorCallback(thrownError);
}
}
});
}
function preLoad() {
if (list.find("#jscroll-loading").length === 0) {
list.find(".jscroll-loadmore").parent("div").remove();
list.append('<a id="jscroll-loading">' + options.loadingButtonText + '</a>');
}
}
//called when doneTyping is called and first time page loaded
jQuery(document).ready(function () {
loadItems();
});
//called when user scrolls down in a div
$('#listNav').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadItems();
}
});
};
})(jQuery);
It's mostly working, but at some cases when user stops typing, the
jQuery(document).ready(function () {
loadItems();
});
and
$('#listNav').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadItems();
}
});
are both called instead of just first one, adding bad html to the div. Most cases only jQuery(document).ready is called, which is what i need.
As well why is jQuery(document).ready() is called every time the doneTyping() is called ? I though it should be called only the first time the page is loaded after DOM is ready.
I assume that your JS code in your HTML starts with a $(document).ready({}), so there would be no need to add $(document).ready({}) inside your plugin. Just call loadItems(); without the document ready event.

How to change onclick event to on mouseover

I am new to javascript I have a doubt in changing onclick event to mouseover please help
<script>
$(document).ready(function() {
(function ($) {
$.fn.readmore = function (settings) {
var opts = $.extend({}, $.fn.readmore.defaults, settings);
this.each(function () {
$(this).data("opts", opts);
if ($(this).html().length > opts.substr_len) {
abridge($(this));
linkage($(this));
}
});
function linkage(elem) {
elem.append(elem.data("opts").more_link);
elem.children(".more").click( function () {
$(this).hide();
$(this).siblings("span:not(.hidden)").hide().siblings("span.hidden").animate({'opacity' : 'toggle'},1000);
});
}
function abridge(elem) {
var opts = elem.data("opts");
var txt = elem.html();
var len = opts.substr_len;
var dots = "<span>" + opts.ellipses + "</span>";
var charAtLen = txt.substr(len, 1);
while (len < txt.length && !/\s/.test(charAtLen)) {
len++;
charAtLen = txt.substr(len, 1);
}
var shown = txt.substring(0, len) + dots;
var hidden = '<span class="hidden" style="display:none;">' + txt.substring(len, txt.length) + '</span>';
elem.html(shown + hidden);
}
return this;
};
$.fn.readmore.defaults = {
substr_len: 500,
ellipses: '…',
more_link: '<a class="more">Read More</a>'
};
})(jQuery);
$(function(){
$('.des_details').readmore({ substr_len: 150 });
});
});
</script>
Any suggestions?
There's a bit of API doc about .hover() which explains what I think you're trying to do. Hope this helps.
http://api.jquery.com/hover/
where you have
elem.children(".more").click( function ()
replace it with
elem.children(".more").hover( function ()
Try this code
$(urid).trigger('mouseover');

Textarea toolbar?

I have been working on a formatting toolbar for a textarea, much like the toolbar for writing questions on this very site (with the bold, italic, underline buttons). The only difference is that I need the buttons to make the text actually bold not just add a bold tag. What I need is similar to the Instructables.com rich comment editor, or the newgrounds.com comment editor, or google docs. Does anyone have a clue how I can make some text in a textarea show up bold, italic, or underlined but keep the rest of it?
There are lots of implementations of javascript WYSIWYG eitors. FCKEditor (now CKEditor) was one of the first. TinyMCE was popular for a long time. I've recently used TinyEditor.
There's also nicedit, 10 editors listed and compared here, not to mention the answers previously provided here on SO to the question of what's available.
An they don't have to produce HTML - there are also editors producing Wiki markup
Why reinvent the wheel?
I found how to create own Rich Text Editor just like this :
(function ($) {
if (typeof $.fn.rte === "undefined") {
var defaults = {
content_css_url: "rte.css",
media_url: "images",
dot_net_button_class: null,
max_height: 350
};
$.fn.rte = function (options) {
$.fn.rte.html = function (iframe) {
return iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
};
var opts = $.extend(defaults, options);
return this.each(function () {
var textarea = $(this);
var iframe;
var myID = textarea.attr("id");
var settings = $.meta ? $.extend({}, opts, textarea.data()) : opts;
var sel = {
cmdBtnSelector: "." + settings.dot_net_button_class
};
function enableDesignMode() {
var content = textarea.val();
if ($.trim(content) == '') {
content = '<br />';
}
if (iframe) {
textarea.hide();
$(iframe).contents().find("body").html(content);
$(iframe).show();
$("#toolbar-" + myID).remove();
textarea.before(toolbar());
return true;
}
iframe = document.createElement("iframe");
iframe.frameBorder = 0;
iframe.frameMargin = 0;
iframe.framePadding = 0;
iframe.height = 200;
if (textarea.attr('class')) iframe.className = textarea.attr('class');
if (textarea.attr('id')) iframe.id = myID;
if (textarea.attr('name')) iframe.title = textarea.attr('name');
textarea.after(iframe);
var css = "";
if (settings.content_css_url) {
css = "<link type='text/css' rel='stylesheet' href='" + settings.content_css_url + "' />";
}
var doc = "<html><head>" + css + "</head><body class='frameBody'>" + content + "</body></html>";
tryEnableDesignMode(doc, function () {
$("#toolbar-" + myID).remove();
textarea.before(toolbar());
textarea.hide();
});
}
function tryEnableDesignMode(doc, callback) {
if (!iframe) {
return false;
}
try {
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(doc);
iframe.contentWindow.document.close();
} catch (error) {
console.log(error)
}
if (document.contentEditable) {
iframe.contentWindow.document.designMode = "On";
callback();
return true;
} else if (document.designMode != null) {
try {
iframe.contentWindow.document.designMode = "on";
callback();
return true;
} catch (error) {
console.log(error)
}
}
setTimeout(function () {
tryEnableDesignMode(doc, callback)
}, 250);
return false;
}
function disableDesignMode(submit) {
var content = $(iframe).contents().find("body").html();
if ($(iframe).is(":visible")) {
textarea.val(content);
}
if (submit !== true) {
textarea.show();
$(iframe).hide();
}
}
function toolbar() {
var tb = $("<div class='rte-toolbar' id='toolbar-" + myID + "'><div>\
<p>\
<select>\
<option value=''>Block style</option>\
<option value='p'>Paragraph</option>\
<option value='h3'>Title</option>\
</select>\
</p>\
<p>\
<a href='#' class='bold'><img src='" + settings.media_url + "text_bold.png' alt='bold' title='Bold' /></a>\
<a href='#' class='italic'><img src='" + settings.media_url + "text_italic.png' alt='italic' title='Italicize' /></a>\
</p>\
<p>\
<a href='#' class='unorderedlist'><img src='" + settings.media_url + "text_list_bullets.png' alt='unordered list' title='Unordered List' /></a>\
<a href='#' class='link'><img src='" + settings.media_url + "link.png' alt='link' title='Hyperlink' /></a>\
<a href='#' class='image'><img src='" + settings.media_url + "image.png' alt='image' title='Image' /></a>\
<a href='#' class='disable'><img src='" + settings.media_url + "code.png' alt='close rte' title='View Code' /></a>\
</p></div></div>");
$('select', tb).change(function () {
var index = this.selectedIndex;
if (index != 0) {
var selected = this.options[index].value;
formatText("formatblock", '<' + selected + '>');
}
});
$('.bold', tb).click(function () {
formatText('bold');
return false;
});
$('.italic', tb).click(function () {
formatText('italic');
return false;
});
$('.unorderedlist', tb).click(function () {
formatText('insertunorderedlist');
return false;
});
$('.link', tb).click(function () {
var p = prompt("URL:");
if (p) formatText('CreateLink', p);
return false;
});
$('.image', tb).click(function () {
var p = prompt("image URL:");
if (p) formatText('InsertImage', p);
return false;
});
$('.disable', tb).click(function () {
disableDesignMode();
var edm = $('Enable design mode');
tb.empty().append(edm);
edm.click(function (e) {
e.preventDefault();
enableDesignMode();
$(this).remove();
});
return false;
});
if (settings.dot_net_button_class != null) {
var cmdBtn = $(iframe).parents('form').find(sel.cmdBtnSelector);
cmdBtn.click(function () {
disableDesignMode(true);
});
} else {
$(iframe).parents('form').submit(function () {
disableDesignMode(true);
});
}
var iframeDoc = $(iframe.contentWindow.document);
var select = $('select', tb)[0];
iframeDoc.mouseup(function () {
setSelectedType(getSelectionElement(), select);
return true;
});
iframeDoc.keyup(function () {
setSelectedType(getSelectionElement(), select);
var body = $('body', iframeDoc);
if (body.scrollTop() > 0) {
var iframe_height = parseInt(iframe.style['height']);
if (isNaN(iframe_height)) {
iframe_height = 0;
}
var h = Math.min(opts.max_height, iframe_height + body.scrollTop()) + 'px';
iframe.style['height'] = h;
}
return true;
});
return tb;
}
function formatText(command, option) {
iframe.contentWindow.focus();
try {
iframe.contentWindow.document.execCommand(command, false, option);
} catch (e) {
console.log(e)
}
iframe.contentWindow.focus();
}
function setSelectedType(node, select) {
while (node.parentNode) {
var nName = node.nodeName.toLowerCase();
for (var i = 0; i < select.options.length; i++) {
if (nName == select.options[i].value) {
select.selectedIndex = i;
return true;
}
}
node = node.parentNode;
}
select.selectedIndex = 0;
return true;
}
function getSelectionElement() {
if (iframe.contentWindow.document.selection) {
selection = iframe.contentWindow.document.selection;
range = selection.createRange();
try {
node = range.parentElement();
} catch (e) {
return false;
}
} else {
try {
selection = iframe.contentWindow.getSelection();
range = selection.getRangeAt(0);
} catch (e) {
return false;
}
node = range.commonAncestorContainer;
}
return node;
}
enableDesignMode();
});
};
}
})(jQuery);
The contentEditable DOM attribute is used make the document or a section of it editable. This doesn't work with a <textarea>; more often an <iframe> is created and the document inside of it used as an editor.
Mark Pilgrim has an article explaining it on the blog of the Web Hypertext Application Technology Working Group. It includes an example page showing some of the features in use.

Categories