Мисля, че е време да ви представя и втората версия на bbcode editor и parser! Тук всичко е написано на jQuery(което прави и библиотеката задължителна). Има и нови функции за offtopic, клипове от vbox7.com и youtube.com, оцветяване на кода(благодарение на prettify). Също така използвам и Алтернативи на alert,confirm и prompt v2 вместо стандартните prompt,confirm и alert функции. Има и други новости, но тях ги оставам на вас да ги разучите :)
За да не трупаме урока с излишни редове си изтеглете prettify и Алтернативи на alert,confirm и prompt v2 . А тук ще ви представя само файловете за самия скрипт за bbcode editor и parser!
bbcode.js
$.fn.bbcodetoolbar = function(data) { //създаваме функцията за показване на bbcode editor-a
var i = $('.toolbar').length;
if ($('.toolbar#tool' + i).is(':visible')) {
i++;
}
var $this = $(this);
var def_data = {
'b' : false,
'i' : false,
'u' : false,
's' : false,
'l' : false,
'c' : false,
'r' : false,
'j' : false,
'list' : false,
'url' : false,
'img' : false,
'imgUrl' : false,
'code' : false,
'quote' : false,
'offtopic' : false,
'player' : false,
'fontcolor' : false,
'fontsize' : false,
'table' : false,
'emoticons' : false
};
if (data) {
var show=[];
datata = data.split(',');
for (var val in def_data) {
show[val] = false;
}
$.each(datata,function(i,v) {
show[v] = true;
});
}
else {
var show=[];
for (var val in def_data) {
show[val] = true;
}
}
$('body').on('click', '.toolbar#tool' + i +' > .button', function() {
var alt = $(this).attr('alt');
$this.addTags('[' + alt + ']', '[/' + alt + ']');
});
$('body').on("change", '.toolbar#tool' + i +' > .fontcolor', function() {
$this.addTags('[color=' + $(this).val() + ']', '[/color]');
});
$('body').on("change", '.toolbar#tool' + i +' > .fontsize', function() {
$this.addTags('[size=' + $(this).val() + ']', '[/size]');
});
$('body').on('click', '.toolbar#tool' + i +' > .unList', function() {
$this.addTags("[list=un]n[*]","[/*]n[/list]");
});
$('body').on('click', '.toolbar#tool' + i +' > .orList', function() {
$this.addTags("[list=or]n[*]","[/*]n[/list]");
});
$('body').on('click', '.toolbar#tool' + i +' > .listItem', function() {
$this.addTags("n[*]","[/*]");
});
$('body').on('click', '.toolbar#tool' + i +' > .addTable', function() {
$this.addTable();
});
$('body').on('click', '.toolbar#tool' + i +' > .btnPicture', function() {
$this.addImage();
});
$('body').on('click', '.toolbar#tool' + i +' > .btnLink', function() {
$this.addUrl();
});
$('body').on('click', '.toolbar#tool' + i +' > .btnLinkPicture', function() {
$this.addImgUrl();
});
$('body').on('click', '.toolbar#tool' + i +' > .vbox7, .toolbar#tool' + i +' > .youtube', function() {
var site = $(this).attr('class').split(' ')[1];
$this.addPlayer(site);
});
$('body').on('click', '.toolbar#tool' + i +' > .showSmiles', function() {
$this.showSmiles();
});
$('body').on('click', '.toolbar#tool' + i +' > .smiles > .emotions', function() {
var alt = $(this).attr('alt');
$this.addTags('', ' ' + alt + ' ');
});
var tools = "";
tools += "<div class="toolbar" id="tool" + i + "">";
if(show['b']) tools += "<img class="button" src="images/bold.gif" alt="b" title="Удебеленяване" />";
if(show['i']) tools += "<img class="button" src="images/italic.gif" alt="i" title="Наклоняване" />";
if(show['u']) tools += "<img class="button" src="images/underline.gif" alt="u" title="Подчертаване"/>";
if(show['s']) tools += "<img class="button" src="images/strike.gif" alt="s" title="Зачеркване"/>";
if(show['l']) tools += "<img class="button" src="images/left.png" alt="l" title="Подравняване в ляво"/>";
if(show['c']) tools += "<img class="button" src="images/center.png" alt="c" title="Подравняване в центъра"/>";
if(show['r']) tools += "<img class="button" src="images/right.png" alt="r" title="Подравняване в дясно"/>";
if(show['j']) tools += "<img class="button" src="images/justify.png" alt="j" title="Двостранно подравняване"/>";
if(show['list']) {
tools += "<img class="function unList" src="images/unordered.gif" title="Списък"/>";
tools += "<img class="function orList" src="images/ordered.gif" title="Списък с номерация"/>";
tools += "<img class="function listItem" src="images/listItem.gif" title="Елемент на списък"/>";
}
if(show['url']) tools += "<img class="function btnLink" src="images/link.gif" title="Добави линк"/>";
if(show['img']) tools += "<img class="function btnPicture" src="images/picture.gif" title="Добави снимка"/>";
if(show['imgUrl']) tools += "<img class="function btnLinkPicture" src="images/linkpic.gif" title="Добави снимка с линк"/>";
if(show['quote']) tools += "<img class="button" src="images/quote.gif" alt="quote" title="Цитат"/>";
if(show['code']) tools += "<img class="button" src="images/code.gif" alt="code" title="Код"/>";
if(show['offtopic']) tools += "<img class="button" src="images/offtopic.gif" alt="offtopic" title="Извън темата"/>";
if(show['player']) {
tools += "<img class="function vbox7" src="images/vbox.png" id="vbox7" title="vbox7"/>";
tools += "<img class="function youtube" src="images/youtube.jpg" id="youtube" title="youtube"/>";
}
if(show['fontcolor']) {tools += "<br /><select name="fontcolor" class="fontcolor">";
tools += "<option value="0" style="color:black">Изберете цвят</option>";
tools += "<option value="black" style="color:black">Черенo</option>";
tools += "<option value="silver" style="color:silver">Сребро</option>";
tools += "<option value="gray" style="color:gray">Сиво</option>";
tools += "<option value="maroon" style="color:maroon">Кестеняво</option>";
tools += "<option value="red" style="color:red">Червено</option>";
tools += "<option value="navy" style="color:navy">Тъмносиньо</option>";
tools += "<option value="blue" style="color:blue">Синьо</option>";
tools += "<option value="green" style="color:green">Зелено</option>";
tools += "<option value="olive" style="color:olive">Маслиненозелено</option>";
tools += "<option value="yellow" style="color:yellow;background-color:red;">Жълто</option>";
tools += "<option value="white" style="color:white;background-color:#ADADAD;">Бяло</option>";
tools += "<option value="purple" style="color:purple">Пурпурен</option>";
tools += "</select>";
}
if(show['fontsize']) {
tools += "<select name="fontsize" class="fontsize">";
tools += "<option value="0">Изберете размер</option>";
tools += "<option value="7">Много малък</option>";
tools += "<option value="9">Малък</option>";
tools += "<option value="12">Нормален</option>";
tools += "<option value="18">Голям</option>";
tools += "<option value="24">Много голям</option>";
tools += "</select>";
}
if(show['table']) {
tools += "Колони: <input type='text' name='tbcols' class='tbcols' size='1' maxlength='2'/>";
tools += "Редове: <input type='text' name='tbrows' class='tbrows' size='1' maxlength='2'/>";
tools += "<input type='button' name='addTable' class='addTable' value='Добави таблица'/>";
}
if(show['emoticons']) tools += "<input type='button' class='showSmiles' value='Емотикони'/><div class='smiles'></div><br />"; //ако не искате да имате smiles махнете този ред!
tools += "</div>";
$this.before(tools);
$this.appendTo('.toolbar#tool' + i);
var dir = "smiles/"; //въведи папката в която са картинките
var title = "";
var link = ['smile.gif', 'sad.gif', 'laught.gif', 'bleh.gif', 'shy.gif', 'cool.gif', 'love.gif', 'angel.gif', 'bye.gif', 'thumbsup.gif', 'chin.gif', 'bop.gif',
'crazy.gif', 'mad.gif', 'spock.gif', 'explode.gif', 'drool.gif', 'popcorn.gif', 'icecream.gif', 'arms.gif', 'baby.gif', 'badday.gif', 'bananadance.gif',
'banned.gif', 'bash.gif', 'beer.gif', 'beer2.gif', 'biggrin.gif', 'blink.gif', 'bouncy.gif', 'bow.gif', 'cake.gif', 'chair.gif', 'cheekkiss.gif', 'cigar.gif',
'clap.gif', 'clover.gif', 'clown.gif', 'confused.gif', 'console.gif', 'cry.gif', 'cry2.gif', 'cupid.gif', 'drinks.gif', 'dry.gif', 'dumbells.gif', 'dunce.gif',
'evil.gif', 'evilmad.gif', 'excited.gif', 'fart.gif', 'fish.gif', 'fishing.gif', 'flowers.gif', 'gathering.gif', 'goodgrief.gif', 'greedy.gif', 'group.gif',
'guns.gif', 'happy.gif', 'happy2.gif', 'happyno.gif', 'happyyes.gif', 'hbd.gif', 'hooray.gif', 'horse.gif', 'hug.gif', 'huglove.gif', 'hump.gif', 'jawdrop.gif',
'kissing.gif', 'kissing2.gif', 'lol.gif', 'look.gif', 'lovers.gif', 'music.gif', 'no.gif', 'ohmy.gif', 'ouch.gif', 'poke.gif', 'puke.gif', 'rant.gif', 'rant2.gif',
'rofl.gif', 'rolleyes.gif', 'shoot.gif', 'shoot2.gif', 'shutup.gif', 'sick.gif', 'slaphead.gif', 'sleep.gif', 'sleeping.gif', 'smartass.gif', 'snap.gif',
'stamp.gif', 'stereo.gif', 'strongbench.gif', 'tears.gif', 'tease.gif', 'therethere.gif', 'thumbsdown.gif', 'unsure.gif', 'wavecry.gif', 'weakbench.gif', 'weirdo.gif',
'what.gif', 'whip.gif', 'whistle.gif', 'wiggle.gif', 'wink.gif', 'worthy.gif', 'wub.gif', 'yawn.gif', 'yikes.gif']; //въведи името на всяка една картинка
var icon = [':)', ':(', ':D', ':P', '(shy)', '8)', '(h)', '(angel)', '(bye)', '(thumbsup)', '(chin)', '(bop)', '(crazy)', '(mad)', '(spock)', ':@', '(drool)',
'(popcorn)', '(icecream)', '(arms)', '(baby)', '(badday)', '(bananadance)', '(banned)', '(bash)', '(beer)', '(beer2)', '(biggrin)', '(blink)', '(bouncy)', '(bow)', '(cake)',
'(chair)', '(cheekkiss)', '(cigar)', '(clap)', '(clover)', '(clown)', '(confused)', '(console)', ';(', ':S', '(cupid)', '(drinks)', '(dry)', '(dumbells)', '(dunce)',
'(evil)', '(evilmad)', '(excited)', '(fart)', '(fish)', '(fishing)', '(flowers)', '(gathering)', '(goodgrief)', '(greedy)', '(group)', '(guns)', '(happy)', '(happy2)',
'(happyno)', '(happyyes)', '(hbd)', '(hooray)', '(horse)', '(hug)', '(huglove)', '(hump)', '(jawdrop)', ':*', '(kissing2)', '(lol)', '(look)', '(lovers)', '(music)', '(no)',
'(ohmy)', '(ouch)', '(poke)', '(puke)', '(rant)', '(rant2)', '(rofl)', '(rolleyes)', '(shoot)', '(shoot2)', ':X', '(sick)', '(slaphead)', '(sleep)', '(sleeping)',
'(smartass)', '(snap)', '(stamp)', '(stereo)', '(strongbench)', '(tears)', '(tease)', '(therethere)', '(thumbsdown)', '(unsure)', '(wavecry)', '(weakbench)', '(weirdo)',
'(what)', '(whip)', '(whistle)', '(wiggle)', ';)', '(worthy)', '(wub)', '(yawn)', '(yikes)']; //въведи съответния текст(иконката) който ще се добавя в textarea-та
jQuery.each(link, function(i, v) { //за всяки веведен линк...
var cont = $('.smiles').html();
title = v.split('.')[0];
$('.smiles').html(cont + "<img src='" + dir + v + "' class="emotions" title=""+title+"" alt="" + icon[i] + ""/> "); //... ще се добавя нов img над textareata
});
}
$.fn.checkSelect = function() { //функция проверяваща дали има селектиран текст
var $this = $(this);
var len = $this.val().length;
var start = $this[0].selectionStart;
var end = $this[0].selectionEnd;
var selectedText = $this.val().substring(start, end);
if (selectedText) return selectedText;
else return false;
}
$.fn.selectRange = function(start, end) {//функция преместваща курсора
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end);
range.select();
}
});
}
$.fn.showSmiles = function() { //функция за показване на списъка с емотиконките
$this = $(this);
$the = $this.parents('.toolbar');
$the.find('.smiles').stop();
var position = $the.find('.showSmiles').position();
var widthsh = $the.find('.showSmiles').width();
var height = $the.find('.showSmiles').height()+7;
var width = $the.find('.smiles').width() / 2;
$the.find('.smiles').css({
left: position.left - width + widthsh,
top: position.top + height
});
if (!$the.find('.smiles').is(':visible')) $the.find('.smiles').slideDown('fast');
var mouse_is_inside = false;
$('.smiles').hover(function() {
mouse_is_inside = true;
}, function() {
mouse_is_inside = false;
});
$("body").mouseup(function() {
if (!mouse_is_inside) $the.find('.smiles').slideUp('fast');
});
}
$.fn.addTags = function(openTag, closeTag) { //функция за добавяне на тагове
if (closeTag == "[/color]" || closeTag == "[/size]") {
$("option[value='0']").attr('selected', 'selected');
} //ако таг2 е [/color] или [/size] при изпълнение на функцията ще се селектне отново първия option
var $this = $(this);
var select = $this.checkSelect();
var scrollTop = $this.scrollTop;
var scrollLeft = $this.scrollLeft;
var len = $this.val().length;
var start = $this[0].selectionStart;
var end = $this[0].selectionEnd;
var selectedText = $this.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
$this.val($this.val().substring(0, start) + replacement + $this.val().substring(end, len));
$this.scrollTop = scrollTop;
$this.scrollLeft = scrollLeft;
var oplen = (openTag != "") ? openTag.length+start : closeTag.length+end ;
var cllen = closeTag.length+end;
if(select) $this.selectRange(end+cllen,end+cllen);
else $this.selectRange(oplen,oplen);
}
$.fn.addPlayer = function(site) {//функция за добавяне на плеъра от vbox7.com или youtube.com
$this = $(this);
var select = $this.checkSelect();
var text;
if (select) {
if(select.indexOf(site+'.com') > -1) $this.addTags("[" + site + "]", "[/" + site + "]");
}
else {
jqcustom('Въведете линк от <a href="http://' + site + '.com" target="_blank">http://' + site + '.com</a>', {
'type': 'prompt',
'title': 'Добавяне на player',
'ok': 'Готово',
'cancel': 'Отказ',
'value': 'http://'
}, function(url) {
if (url && url != 'http://' && url.indexOf(site+'.com') > -1 ) {
text = "[" + site + "]" + url + "[/" + site + "]";
$this.addTags('', text);
}
});
}
}
$.fn.addTable = function() { //функция за създаване на таблица
var $this = $(this); //взимаме id-то на textarea-та
$the = $this.parents('.toolbar');
var rows = $the.find('.tbrows').val(); //стойноста на input rows т.е колко реда да има таблицата
var cols = $the.find('.tbcols').val(); //стойноста на input cols т.е колко колони да има таблицата
var text = "n[table]n";
for (i = 1; i <= rows; i++) { //за всяки ред добавяме код за редове
text += "[tr]n";
for (k = 1; k <= cols; k++) { //за всяки колона добавяме код за колона
text += "[td]";
text += "[/td]n";
}
text += "[/tr]n";
}
text += "[/table]n";
if (cols > 0 && rows > 0) $this.addTags('', text); //добавяме таблицата към textarea-та
$the.find('.tbrows').val("");
$the.find('.tbcols').val(""); //изчистваме 2-та input-а
}
$.fn.addImage = function() { //функция за добавяне на снимка
$this = $(this);
var text;
var select = $this.checkSelect();
if (select) {
$this.addTags('[img]', '[/img]');
} else {
jqcustom('Въведи линк към картинката', {
'type': 'prompt',
'title': 'Добавяне на картинката',
'ok': 'Готово',
'cancel': 'Отказ',
'value': 'http://'
}, function(url) {
if (url && url != 'http://') {
text = '[img]' + url + '[/img]';
$this.addTags('', text);
}
});
}
}
$.fn.addUrl = function() { //функция за добавяне на линк
$this = $(this);
var text;
var select = $this.checkSelect();
jqcustom('Въведете линк', {
'type': 'prompt',
'title': 'Добавяне на линк',
'ok': 'Готово',
'cancel': 'Отказ',
'value': 'http://'
}, function(url) {
if (url && url != 'http://') {
if (select) {
$this.addTags('[url=' + url + ']', '[/url]');
} else {
jqcustom('Въведете име на линка', {
'type': 'prompt',
'title': 'Добавяне на линк',
'ok': 'Готово',
'cancel': 'Отказ'
}, function(url2) {
url2 = (url2) ? url2 : "link";
text = '[url=' + url + ']' + url2 + '[/url]';
$this.addTags('', text);
});
}
}
});
}
$.fn.addImgUrl = function() { //функция за добавяне на снимка с линк
$this = $(this);
var text;
var select = $this.checkSelect();
jqcustom('Въведете линк', {
'type': 'prompt',
'title': 'Добавяне на линк с картинка',
'ok': 'Готово',
'cancel': 'Отказ',
'value': 'http://'
}, function(url) {
if (url && url != 'http://') {
if (select) {
$this.addTags('[img=' + url + ']', '[/img]');
} else {
jqcustom('Въведи линк към картинката', {
'type': 'prompt',
'title': 'Добавяне на линк с картинка',
'ok': 'Готово',
'cancel': 'Отказ',
'value': 'http://'
}, function(url2) {
if (url2 && url2 != 'http://') {
text = '[img=' + url + ']' + url2 + '[/img]';
$this.addTags('', text);
}
});
}
}
});
}
$(function() {
$(".showoff").click(function() { //скрипт за показване съдържанието на offtopic
$(this).parents(".offtable").find(".offtopic").toggle();
});
});