Показаны сообщения с ярлыком jQuery. Показать все сообщения
Показаны сообщения с ярлыком jQuery. Показать все сообщения

воскресенье, 30 ноября 2014 г.

Счетчик введенных символов JQUERY




<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>textArea</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>

<div><textarea id="messageText" cols="45" rows="15"></textarea></div>

<div>Количество символов: <span id="symbolsCounter"></span></div>

 
<script type="text/javascript">
$(function() {
    var ta = $("#messageText");
    var counter = $("#symbolsCounter");
    counter.html(ta.val().length);
    if ($.browser.mozilla && $.browser.version.substr(0,3)=="1.9") {
        ta.bind("input", function() {
            updateCounter();
        });
    }
    else {
        ta.bind("keyup", function() {
            updateCounter();
        });
    }



    function updateCounter() {
        counter.html(ta.val().length);
        var split = ta.val().split("\n");
        if (split.length > 15) {
            ta.attr("rows", split.length);
        }
    }
});
</script>
</body>
</html> 

суббота, 18 января 2014 г.

Реализация Local Storage на Jquery


Реализация Local Storage на Jquery


/**
* Storage plugin
* Provides a simple interface for storing data such as user preferences.
* Storage is useful for saving and retreiving data from the user's browser.
* For newer browsers, localStorage is used.
* If localStorage isn't supported, then cookies are used instead.
* Retrievable data is limited to the same domain as this file.
*
* Usage:
* This plugin extends jQuery by adding itself as a static method.
* $.Storage - is the class name, which represents the user's data store, whether it's cookies or local storage.
* <code>if ($.Storage)</code> will tell you if the plugin is loaded.
* $.Storage.set("name", "value") - Stores a named value in the data store.
* $.Storage.set({"name1":"value1", "name2":"value2", etc}) - Stores multiple name/value pairs in the data store.
* $.Storage.get("name") - Retrieves the value of the given name from the data store.
* $.Storage.remove("name") - Permanently deletes the name/value pair from the data store.
*
* @author Dave Schindler
*
* Distributed under the MIT License
*
* Copyright (c) 2010 Dave Schindler
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function($) {
// Private data
var isLS=typeof window.localStorage!=='undefined';
// Private functions
function wls(n,v){var c;if(typeof n==="string"&&typeof v==="string"){localStorage[n]=v;return true;}else if(typeof n==="object"&&typeof v==="undefined"){for(c in n){if(n.hasOwnProperty(c)){localStorage[c]=n[c];}}return true;}return false;}
function wc(n,v){var dt,e,c;dt=new Date();dt.setTime(dt.getTime()+31536000000);e="; expires="+dt.toGMTString();if(typeof n==="string"&&typeof v==="string"){document.cookie=n+"="+v+e+"; path=/";return true;}else if(typeof n==="object"&&typeof v==="undefined"){for(c in n) {if(n.hasOwnProperty(c)){document.cookie=c+"="+n[c]+e+"; path=/";}}return true;}return false;}
function rls(n){return localStorage[n];}
function rc(n){var nn, ca, i, c;nn=n+"=";ca=document.cookie.split(';');for(i=0;i<ca.length;i++){c=ca[i];while(c.charAt(0)===' '){c=c.substring(1,c.length);}if(c.indexOf(nn)===0){return c.substring(nn.length,c.length);}}return null;}
function dls(n){return delete localStorage[n];}
function dc(n){return wc(n,"",-1);}
/**
* Public API
* $.Storage - Represents the user's data store, whether it's cookies or local storage.
* $.Storage.set("name", "value") - Stores a named value in the data store.
* $.Storage.set({"name1":"value1", "name2":"value2", etc}) - Stores multiple name/value pairs in the data store.
* $.Storage.get("name") - Retrieves the value of the given name from the data store.
* $.Storage.remove("name") - Permanently deletes the name/value pair from the data store.
*/
$.extend({
Storage: {
set: isLS ? wls : wc,
get: isLS ? rls : rc,
remove: isLS ? dls :dc
}
});
})(jQuery);



Использование:

Сначала подключаем библиотеку jQuery и вышеуказанную библиотеку:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script><script src="jquery.Storage.js"></script>
Мы будем сохранять в браузере то, что пользователь прокомментировал:
 
function data_storage() { //__ read storage
    var user = $.Storage.get('user');
    var message = $.Storage.get('message');
    //__ set targets
    if (user) $('input[name="user"]').val(unescape(user));
    if (message) $('textarea[name="message"]').val(unescape(message));
    //__ write storage
    $('#comment').submit(function () {
        if ($('input[name="user"]').length)
            $.Storage.set('user', escape($('input[name="user"]').val()));
        if ($('textarea[name="message"]').length)
            $.Storage.set('message', escape($('textarea[name="message"]').val()));
    });
}
// End storage 
Для формы в HTML:


<form action="" method="post" id="comment">
  Ваше имя: <br />
  <input name="user" type="text" size="25" /><p></p>
  Сообщение: <br />
  <textarea name="message" cols="55" rows="5"></textarea><p></p>
  <input name="id" type="hidden" value="7" />
  <input name="send" type="submit" class="btn btn-default" value="Оставить отзыв" />
</form>


Проверить поддерживает ли браузер LocalStorage можно так:


function isLocalStorageAvailable() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; }} isLocalStorageAvailable();

Без Jquery можно было бы сделать так:


Сохранение данных:
localStorage.setItem('foo', 'bar');


Извлечение данных:
var foo = localStorage.getItem('foo');alert(foo); //bar



Можно использовать объектную нотацию для сохранения и извлечения данных:
localStorage['foo'] = 'bar';var foo = localStorage['foo'];alert(foo); //bar



Удаление данных:
localStorage.removeItem('foo'); //удалит элемент объектаlocalStorage.clear(); //удалит все элементы


Проверим превысили ли ограничение размера локального хранилища
try { localStorage.setItem('foo', 'bar');} catch (e) { if (e == QUOTA_EXCEEDED_ERR) { alert('Локальное хранилище переполнено'); }}

Однако так сохранять можно только строковые данные. 
Иногда требуется сохранять объекты - надо воспользоваться сериализацией:
var foo = {1: [1, 2, 3]};localStorage.setItem('foo', JSON.stringify(foo));var fooFromLS = JSON.parse(localStorage.getItem('foo'));




пятница, 17 января 2014 г.

Скелет плагина на jQuery с использованием методов

Скелет плагина на jQuery с использованием методов


(function($){
    var methods = {
        init : function(options) {
            console.log('init');
        },
        show : function( ) {
     
        },
        hide : function( ) {
     
        },
        update : function(content) {
            console.log(content);
        }
    };
    $.myPlug = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Метод с именем ' +  method + ' не существует для $.chats' );
        }
    };
})(jQuery);
$.myPlug(); // init
$.myPlug('update', 'Привет мир'); // Привет мир
$.myPlug('blalbla') // $.error



или

$.tooltip = {
  update: function() {},
  init: function() {},
  show: function() {} // и т.п.
}

и вызывать как $.tooltip.show()

суббота, 14 декабря 2013 г.

Расширение для Chrome с ВКонтакте скачивать музыку своими руками

Расширение для Chrome с ВКонтакте скачивать музыку своими руками 

Первым делом, самое главное - создаем файл яваскрипта script.js:


$(document).ready(function () {
    chrome.tabs.getSelected(null, function (tab) {
        var url = tab.url;
        if (url.indexOf("http://vk.com/audio") > -1) {
            xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.send(null);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.responseText) {
                        var data = xhr.responseText;
                        var newS = '';
                        $('.audio', data).each(function (index) {
                            var title = $(this).children('.area').children('.info').children('.title_wrap').text();
                            var href = $(this).children('.area').children('.play_btn').children('input').val();
                            href = href.substring(0, href.indexOf('.mp3') + 4);
                            title = '<a href="' + href + '" download>' + title + '</a>';
                            $('#wrapper').append(title + '<br />');
                        });
                    }
                }
            }
        } else {
            $('#wrapper').html('Audio is empty');
        }
    });
});


Далее создаем манифест файл manifest.json:

{
"manifest_version":2,
"name":"VK",
"version":"1.0",
"description":"VK",
"permissions": [
"http://vk.com/*",
"tabs"
],
"browser_action": {
"default_title":"VK",
"default_icon":"icon.png",
"default_popup":"popup.html"
}
}


Файл popup.html

<!DOCTYPE html>
<html>
<head>
<meta charset="windows-1251" />
<title>Document</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="jquery.js"></script>
<script src="script.js"></script>
<style>
*{margin:0; padding:0;}
a, a:visited{color:#0857a6}
body{width:1000px;padding:10px;font-family:Trebuchet MS, Arial, Tahoma, Sans;overflow:auto;}
</style>
</head>
<body>
<div id="wrapper"></div>
</body>
</html>

Не забудьте создать иконку icon.png и подключить jquery
например так
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
но лучше скачать его и сделать локальным.


среда, 20 ноября 2013 г.

jQuery: close popup by click on body

Чтобы скрыть всплывающее окно по клику снаружи:


$("body").click(function(e) {
    if($(e.target).closest(".popup").length==0) $(".popup").css("display","none");
});

суббота, 21 сентября 2013 г.

Почистить папку в Yandex почте с огромным числом писем на jQuery

Почистить папку в Yandex почте с огромным числом писем на jQuery  

В настройках поставьте максимальное число отображаемых писем (200), иначе по умолчанию будет удалять только по 20 писем, далее выделяем все видимые письма в папке, нажимаем кнопку удалить, повторяем процедуру через 5 секунд.


(function(){
 $('.block-messages-list-box.b-layout__first-pane input[type=checkbox]:not(:first)').trigger('click').trigger('click');
 $('a.b-toolbar__item.b-toolbar__item_delete.daria-action').click();
 setTimeout(arguments.callee,5000);
})();
Удаленные письма попадают в папку «Удаленные». Которая тоже штатными средствами не чистится. Придется повторить процедуру дважды.

Возвращаем в jQuery $.browser

Возвращаем в jQuery $.browser - в новых версиях  jQuery $.browser не работает, потому существует такой костыль:

(function() {

    var matched, browser;

// jQuery.uaMatch поддерживается для совместимости  
jQuery.uaMatch = function( ua ) {
        ua = ua.toLowerCase();

        var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
            /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
            /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
            /(msie) ([\w.]+)/.exec( ua ) ||
            ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
            [];

        return {
            browser: match[ 1 ] || "",
            version: match[ 2 ] || "0"
        };
    };

    matched = jQuery.uaMatch( navigator.userAgent );
    browser = {};

    if ( matched.browser ) {
        browser[ matched.browser ] = true;
        browser.version = matched.version;
    }

// Chrome is Webkit, but Webkit is also Safari.
    if ( browser.chrome ) {
        browser.webkit = true;
    } else if ( browser.webkit ) {
        browser.safari = true;
    }

    jQuery.browser = browser;

    jQuery.sub = function() {
        function jQuerySub( selector, context ) {
            return new jQuerySub.fn.init( selector, context );
        }
        jQuery.extend( true, jQuerySub, this );
        jQuerySub.superclass = this;
        jQuerySub.fn = jQuerySub.prototype = this();
        jQuerySub.fn.constructor = jQuerySub;
        jQuerySub.sub = this.sub;
        jQuerySub.fn.init = function init( selector, context ) {
            if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
                context = jQuerySub( context );
            }

            return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
        };
        jQuerySub.fn.init.prototype = jQuerySub.fn;
        var rootjQuerySub = jQuerySub(document);
        return jQuerySub;
    };

})();


вторник, 20 августа 2013 г.

JSONP API: vk, wikipedia, Flickr


VK используя JSONP API


<script>
$(function (){
var textto = '';
$.getJSON('http://api.vk.com/method/wall.get?owner_id=-47211921&filter=owner&count=2&callback=?', function (data) {
    for (var i = 1; i < 10; i++) {
        $("#to").append(data.response[i].text);
    }
});
 
});  
</script>
<p id="to"></p>




Flickr используя JSONP API




<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });
</script>
<div id="images"></div>










WIKIPEDIA используя JSONP API


<script>
(function($) {
 $.fn.TexWikiPlugin =function(){
var url = "http://ru.wikipedia.org/wiki/Третьякова_Лена";
var title = url.split("/");
title = title[title.length - 1];
var url2 = "http://ru.wikipedia.org/wiki/Третьякова_Лена (группа)";
var title2 = url.split("/");
title2 = title2[title2.length - 1];
try
{
//Get Leading paragraphs (section 0)
$.getJSON("http://ru.wikipedia.org/w/api.php?action=parse&page=" + title + "&prop=text&section=0&format=json&callback=?", function (data) {
for (text in data.parse.text) {
var text = data.parse.text[text].split("<p>");
var pText = "";
for (p in text) {
//Remove html comment
text[p] = text[p].split('<!--');
if (text[p].length > 1) {
text[p][0] = text[p][0].split(/\r\n|\r|\n/);
text[p][0] = text[p][0][0];
text[p][0] += '</p> ';
}
text[p] = text[p][0];
//Construct a string from paragraphs
if (text[p].indexOf('</p>') == text[p].length - 5) {
var htmlStrip = text[p].replace(/<(?:.|\n)*?>/gm, '') //Remove HTML
var splitNewline = htmlStrip.split(/\r\n|\r|\n/); //Split on newlines
for (newline in splitNewline) {
if (splitNewline[newline].substring(0, 11) != "Site error:") {
pText += splitNewline[newline];
pText += '\n';
}
}
}
}
pText = pText.substring(0, pText.length - 2); //Remove extra newline
pText = pText.replace(/\[\d+\]/g, ''); //Remove reference tags (e.x. [1], [4], etc)

document.getElementById('div_text').innerHTML = pText
}
});
}
catch(err)
{
console.log('Исключение: '+err.description);
}
 return this;
 };
 setTimeout(function() {  
        $.fn.TexWikiPlugin();
    }, 1500);
})(jQuery);
</script>
<div id="div_text"></div>

Google Images Parser



  PHP

// Google Img
$keyword = urlencode(str_replace(' ','+',$tickets_name));
$jsrc = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$keyword;
$json = @file_get_contents($jsrc);
$jset = json_decode($json, true);
echo '<div style="height:200px;">
<img src="'.$jset["responseData"]["results"][0]["url"].'" style="border:4px solid #ddd;height:200px;float:right;" />';
echo  '</div><br /> ';

Jquery


<script>
function myjsonpfunction2(data){
   // console.log(data.responseData.results)
   $.each(data.responseData.results,function(i,rows){
    // console.log(rows.url);
$('#gooimg2').append('<img style="border:4px solid #ddd;height:200px;" src="'+rows.url+'" />');
   });
}
$(function(){
    $.ajax({
        url: 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=<?php echo $keyword ; ?>&callback=myjsonpfunction2',
    type:"GET",
    dataType: 'jsonp',
    jsonp: 'myjsonpfunction2',
    async:'true',
    success:function (data) {
     console.log("success");
    }
    });
  });
</script>
<div id="gooimg2" style="height:200px;"></div><br /> 

* Можно добавить return false; внутри $.each, чтобы остановить цикл и выбрать первую запись. 

суббота, 3 августа 2013 г.

jQuery: Скроллинг контента пальцем | Finger Scrolling

jQuery: Скроллинг контента пальцем |  Finger Scrolling


  1. jQuery.fn.oneFingerScroll = function() {
  2. var scrollStartPos = 0;
  3. $(this).bind('touchstart', function(event) {
  4.  
  5. var e = event.originalEvent;
  6. scrollStartPos = $(this).scrollTop() + e.touches[0].pageY;
  7. e.preventDefault();
  8. });
  9. $(this).bind('touchmove', function(event) {
  10. var e = event.originalEvent;
  11. $(this).scrollTop(scrollStartPos - e.touches[0].pageY);
  12. e.preventDefault();
  13. });
  14. return this;
  15.  
  16. };
  17.  
  18. // example
  19. $('#scrolling').oneFingerScroll();

jQuery: Growl-like messages

jQuery: Growl-like messages



  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
  1. <style>
  2. .error_box {
  3. display: none;
  4. border: 1px solid #f7c7c9;
  5. background: #f9e5e6;
  6. position: fixed;
  7. width: 370px;
  8. right: 20px;
  9. top: 20px;
  10. -webkit-box-shadow: 0px 5px 5px 3px rgba(0, 0, 0, 0.3);
  11. box-shadow: 0px 5px 5px 3px rgba(0, 0, 0, 0.3);
  12. -webkit-border-radius: 5px;
  13. border-radius: 5px;
  14. text-align: center;
  15. }
  16.  
  17. .error_message {
  18. color: #c77c7e;
  19. margin-top: 18px;
  20. font-weight: bold;
  21. text-shadow: 1px 1px 1px #FFFFFF;
  22. filter: dropshadow(color=#FFFFFF, offx=1, offy=1);
  23. }
  24. </style>


  25.  
  26. <div id="error_box" class="error_box">
  27. <p id="error_message" class="error_message"></p>
  28. </div>
  29.  
  30. <script>
  31. function throw_message(str) {
  32. $('#error_message').html(str);
  33. $("#error_box").fadeIn(500).delay(3000).fadeOut(500);
  34. }
  35. </script>
  36.  
  37. <a href='#' onclick='throw_message("It Was Clicked"); return false;'>Click it!</a>

jQuery: Display file sizes next to download links

jQuery: Display file sizes next to download links


  1. // Loop all links on page with class .getSize
  2. $('a.getSize').each(function(){
  3. // Issue an AJAX HEAD request for each one
  4. var link = this;
  5. $.ajax({
  6. type: 'HEAD',
  7. url: link.href,
  8. complete: function(xhr){
  9. var size = humanization(xhr.getResponseHeader('Content-Length'));
  10. // Append the filesize to each
  11. $(link).append(' (' + type + ')');
  12. }
  13. });
  14. });
  15. function humanization(size){
  16. var units = ['bytes','KB','MB','GB','TB','PB'];
  17. var ord = Math.floor( Math.log(size) / Math.log(1024) );
  18. ord = Math.min( Math.max(0,ord), units.length-1);
  19. var s = Math.round((size / Math.pow(1024,ord))*100)/100;
  20. return s + ' ' + units[ord];
  21. }
  22. // example html
  23. // <a href="one.html" class="getSize">Some link</a>
  24. // <a href="other.html" class="getSize">Other link</a>
  25. // <a href="car.jpg" class="getSize">Image</a>


jQuery: Обнаружение изменения ориентации экрана

jQuery: Обнаружение изменения ориентации экрана


  1. $(window).bind('orientationchange', function(event) {
  2. someFunction();
  3. });


Постоянные читатели

Популярные сообщения