jQuery 페이지 또는 객체에서 특정 키워드 강조하기

Open API/Jquery|2016. 11. 17. 10:59
반응형


특정 페이지 또는 객체에서 키워드 찾는 함수..


1원짜리는 아니고...3원쯤의 가치가..;;



Test Url : http://www.uhoon.co.kr/test/3143.html



<!DOCTYPE html>
<html>
 
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>KeyWord Highlights</title> 
    <script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
    </head> 
    <script type="text/javascript">
    <!-- 
        $(document).ready(function(){
            fnKeyWordHighlights("p","감기");
        });
 
        function fnKeyWordHighlights(obj,keyword)
        {
            $(obj).each(function(){  
                $(this).html($(this).html().replace(eval("/"+keyword+"/gi"), "<span style='color:red;font-weight:bold;'>"+keyword+"</span>"));
            });
        } 
    //-->
    </script>
</head>
<body > 
    <p>나는 오늘 감기에 걸렸다. 지겨운 감기.. 너무 싫다.</p>
</body> 
</html>


댓글()

jQuery Star Rating Plugin - 별점 주기

Open API/Jquery|2016. 11. 16. 10:38
반응형



별점 주기 플러그인입니다.


가끔 유용하게 사용하는 기능 쓸라면 코딩하기 귀찮은.....( _ _)..


Plugin Url : http://wbotelhos.com/raty


DownLoad : https://github.com/wbotelhos/raty


(기본 샘플외에도 많은 기능이 있습니다.)



Test Url : http://www.uhoon.co.kr/test/6979.html


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="Pragma" content="no-cache"/>
        <meta http-equiv="Expires" content="-1"/>
        <title>jQuery Raty - A Star Rating Plugin</title>
 
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript" src="/test/2979/js/jquery.raty.js"></script>
 
    </head>
    <body>
        <div id="star" ></div>
 
        <div style="padding-top:20px;">
            <label for="starRating">Value : </label><input type="text" id="starRating" value="3"/>
        </div>
 
        <div style="padding-top:20px;">
            <label for="displayStarRating">Value : </label><span id="displayStarRating" style="padding-left:20px;">3</span>
        </div>
    </body>
 
    <script type="text/javascript">
        $(function() {
            $('div#star').raty({
                score: 3
                ,path : "/test/2979/img"
                ,width : 200
                ,click: function(score, evt) {
                    $("#starRating").val(score);
                    $("#displayStarRating").html(score);
                }
            });
        });
    </script>
</html>

옵션


cancel      : false                                          // Creates a cancel button to cancel the rating.
cancelHint  : 'Cancel this rating!'                          // The cancel's button hint.
cancelOff   : 'cancel-off.png'                               // Icon used on active cancel.
cancelOn    : 'cancel-on.png'                                // Icon used inactive cancel.
cancelPlace : 'left'                                         // Cancel's button position.
click       : undefined                                      // Callback executed on rating click.
half        : false                                          // Enables half star selection.
halfShow    : true                                           // Enables half star display.
hints       : ['bad', 'poor', 'regular', 'good', 'gorgeous'] // Hints used on each star.
iconRange   : undefined                                      // Object list with position and icon on and off to do a mixed icons.
mouseout    : undefined                                      // Callback executed on mouseout.
mouseover   : undefined                                      // Callback executed on mouseover.
noRatedMsg  : 'Not rated yet!'                               // Hint for no rated elements when it's readOnly.
number      : 5                                              // Number of stars that will be presented.
numberMax   : 20                                             // Max of star the option number can creates.
path        : ''                                             // A global locate where the icon will be looked.
precision   : false                                          // Enables the selection of a precision score.
readOnly    : false                                          // Turns the rating read-only.
round       : { down: .25, full: .6, up: .76 }               // Included values attributes to do the score round math.
score       : undefined                                      // Initial rating.
scoreName   : 'score'                                        // Name of the hidden field that holds the score value.
single      : false                                          // Enables just a single star selection.
size        : 16                                             // The size of the icons that will be used.
space       : true                                           // Puts space between the icons.
starHalf    : 'star-half.png'                                // The name of the half star image.
starOff     : 'star-off.png'                                 // Name of the star image off.
starOn      : 'star-on.png'                                  // Name of the star image on.
target      : undefined                                      // Element selector where the score will be displayed.
targetFormat: '{score}'                                      // Template to interpolate the score in.
targetKeep  : false                                          // If the last rating value will be keeped after mouseout.
targetText  : ''                                             // Default text setted on target.
targetType  : 'hint'                                         // Option to choose if target will receive hint o 'score' type.
width       : undefined                                      // Manually adjust the width for the project.

댓글()

jQuery Plugin For Auto Resizing iFrame - iFrame Resizer

Open API/Jquery|2016. 11. 16. 10:35
반응형



* 크로스 도메인 iFrame Resize 플러그인


* Plugin Url : http://www.jqueryscript.net/layout/jQuery-Plugin-For-Auto-Resizing-iFrame-iFrame-Resizer.html



iFrame 사용시 Height Resize 문제가 가장 어려웠습니다만..

이론상으로 참고할 만한 블로그는 http://johan.driessen.se/posts/resizing-cross-domain-iframes 를 ...

쉽게 생각하면 아래 이미지 한컷으로 정리가 될것입니다.



iframe-resizer-master.zip


* 부모창


<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>iFrame message passing test</title> 
<meta name="description" content="iFrame message passing test"> 
<meta name="viewport" content="width=device-width">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head> 
<body> 
  
<h2>Automagically resizing iFrame</h2>
<p>Resize window or click 'Toggle content' to watch iFrame resize</p>
<div style="margin:20px;">
<iframe src="frame.content.html" width="100%" scrolling="no"></iframe>
</div>
<p id="callback">
</p>
  
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="../js/jquery.iframeResizer.min.js"></script> 
<script type="text/javascript">
$('iframe').iFrameSizer({
     log                    : true,  // For development
     autoResize             : true,  // Trigering resize on events in iFrame
     contentWindowBodyMargin: 8,     // Set the default browser body margin style (in px)
     doHeight               : true,  // Calculates dynamic height
     doWidth                : false, // Calculates dynamic width
     enablePublicMethods    : true,  // Enable methods within iframe hosted page 
     interval               : 0,     // interval in ms to recalculate body height, 0 to disable refreshing
     scrolling              : false, // Enable the scrollbars in the iFrame
     callback               : function(messageData){ // Callback fn when message is received
          $('p#callback').html(
               '<b>Frame ID:</b> '    + messageData.iframe.id +
               ' <b>Height:</b> '     + messageData.height +
               ' <b>Width:</b> '      + messageData.width + 
               ' <b>Event type:</b> ' + messageData.type
          );
     }
});
</script>
</body> 
</html>

*자식창


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>iFrame message passing test</title>
        <meta name="description" content="iFrame message passing test">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <style>
            a { float:right; margin-left:10px;}
        </style>
    </head>
    <body>
 
        <b>iFrame</b>
        <a href='#' onclick="$('p:eq(0)').toggle();return false;">Toggle content</a>
          
        <a href='#' onclick="if ('parentIFrame' in window) window.parentIFrame.size(250);return false;">Size(250)</a>
          
        <a href='#' onclick="if ('parentIFrame' in window)  window.parentIFrame.close();return false;">Close</a>
 
        <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </p>
        <p>
            But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?
        </p>
        <p>
            On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.
        </p>
 
 
        <script type="text/javascript" src="iframeResizer.contentWindow.min.js"></script>
    </body>
</html>


댓글()

jQuery 우클릭 , 셀 선택 , 드래그 방지 스크립트

Open API/Jquery|2016. 11. 16. 10:23
반응형




브라우저 개발자 도구등 각종 우회 방법이 있습니다만.


우클릭 , 셀 선택 , 드래그 방지 스크립트 입니다.

$(document).ready(function(){  
    $(document).bind("contextmenu", function(event){event.preventDefault();});
    //마우스 우클릭 방지
    $(document).bind("selectstart", function(event){event.preventDefault();});
    //더블클릭으로 셀선택 방지
    $(document).bind("dragstart", function(event){event.preventDefault();});
    //드래그 방지
});

댓글()

JQuery Load 유무 체크하기

Open API/Jquery|2016. 11. 16. 09:41
반응형



페이지 내에 Jquery 가 정상적으로 load 되었는지 체크 하는 방법입니다.


종종 해외 특정 국가의 경우 


jQuery 사이트의 jquery.js 파일 include 시에 정상적으로


읽어오지 못하는 경우가 발생합니다.


혹은 인터넷 속도 문제로 타 도메인의 jquery.js 사용할 경우에도 발생합니다.


가급적 동일 호스팅에 있는 파일을 이용하시길 권장합니다.



// 1.
if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}
 
// 2.
if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}
 
// .. 만약 Load 되어있지 않다면.. 추가하기
if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  jq.src = 'http://code.jquery.com/jquery-latest.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

댓글()

jQuery-syaku.rolling 상하좌우 롤링 ( 자동롤링 , 버튼 )

Open API/Jquery|2016. 11. 15. 17:28
반응형



그간 많은 롤링플러그인을 사용해왔으나 이해하기도 쉽고 적용하기도 쉽고 응용하기도 쉽고 TOP 입니다!!

최석균님(제작자)께 감사드립니다. 


Test Url : http://www.uhoon.co.kr/test/2544.html



플러그인 및 샘플 다운로드 ( jquery-syaku.rolling.v1.2.0.zip )


* 제작자님 샘플에는 Javascript 배열에 객체를 직접 담아하도록 되어있으나 

현업에서 편의상 html 태그를 Js에 넣어서 사용하기 힘든바 html 소스에서 읽어와서 

롤링되도록 샘플소스에 적용하였으니 참고해주세요 .


첨부된 샘플 소스는 제작자님께서 제공하시는 그대로입니다.

하여 쬐끔 수정한 샘플 소스자체를 아래 작성합니다.


<!DOCTYPE html>
<html>
<head>
    <title>상하좌우 롤링 ( 버튼 , 자동 )</title>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="./2544/jquery-syaku.rolling.js"></script>
    <script type="text/javascript">
        jQuery(function() {
 
            jQuery("#srolling").srolling({
                data : $("#aaa > div"),  // 노출될 아이템
                auto : true,                    //자동 롤링 true , false
                width : 20,                 // 노출될 아이템 크기
                height : 30,                    // 노출될 아이템 크기
                item_count : 1,         // 이동 될 아이템 수
                cache_count : 1,            // 임시로 불러올 아이템 수
                delay : 1000,               // 이동 아이템 딜레이
                delay_frame : 500,      // 아이템 흐르는 속도
                move : 'top',               // 이동 방향 left , right , top , down
                prev : '#p_click',          // < 이동 버튼
                next : '#n_click'           // > 이동 버튼
            });
        });
    </script>
</head>
 
<body >
<div id="srolling" style="position: relative;overflow:hidden;width:100px;height:30px;border:#e0e2ef 1px solid;"></div>
<div id="aaa" style="display:none;">
    <div>11111</div>
    <div>22222</div>
    <div>33333</div>
    <div>44444</div>
    <div>55555</div>
    <div>66666</div>
</div>
<span id="p_click">이전</span>
<span id="n_click">다음</span>
</body>
</html>


댓글()

jQuery Table에 동적 Tr 추가/삭제 하기

Open API/Jquery|2016. 11. 15. 17:23
반응형


관리자 페이지등에서 잊을만 하면 사용하는 기능인데..


그간 샘플링이 안되어서 매번 그때 그때 커스터마이징해서 썻던것인데 정리해보았습니다.


Test Url : http://www.uhoon.co.kr/test/2541.html 



<!DOCTYPE html>
<html>
<head>
    <title>테이블에 동적으로 TR 추가 /삭제 하기</title>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#btnAddRow").on("click",function() {
                // clone
                $.trClone = $("#memberTable tr:last").clone().html();
                $.newTr = $("<tr>"+$.trClone+"</tr>");
 
                // append
                $("#memberTable").append($.newTr);
 
                // delete Button 추가
                $.btnDelete = $(document.createElement("input"));
                $.btnDelete.attr({
                    name : "btnRemove",
                    type : "button" ,
                    value : "삭제"
                });
                $("#memberTable tr:last td:last").html("");
                $("#memberTable tr:last td:last").append($.btnDelete);
 
                // 버튼에 클릭 이벤트 추가
                $("#memberTable tr>td:last>input[type='button']").on('click', function(){
                    $(this).parent().parent().remove();
                });
            });
 
            // 초기화
            $("#tableReset").on("click",function(){ 
                $("#frmTest").each(function(){ this.reset(); });
 
                $("input[name='btnRemove']").each(function () {
                    $(this).trigger('click');
                });
            });
        });
    </script>
</head>
 
<body >
<div style="width:500px;text-align:right;">
    <input type="button" value="행추가"  id="btnAddRow" />
    <input type="button" value="reset" id="tableReset"/>
</div>
 
 
<form method="post" id="frmTest">
<table id="memberTable" border="1" style="width:500px;">
    <tr>
        <td><input type="text" id="fullName" /></td>
        <td><input type="text" id="age"  /></td>
        <td><input type="text" id="addr" /></td>
        <td style="width:50px;"></td>
    </tr>
</table>
</form>
</body>
</html>


댓글()

jQuery 한글/영어 byte 체크해서 자르기

Open API/Jquery|2016. 11. 15. 17:21
반응형



SMS 발송 폼 처리 중 80 바이트 체크하기 위해서..

사용 편의를 위해 일부 내용이 수정되었습니다.


원개발자분께 감사드립니다. ( http://blog.naver.com/yesdouble/130152964039 )


Test Url : http://www.uhoon.co.kr/test/2410.html

<!DOCTYPE html>
<html>
<head>
	<title>한글/영어 byte 체크해서 자르기</title>
	<script src="http://code.jquery.com/jquery-latest.min.js"></script>
	<meta http-equiv="content-type" content="text/html;charset=UTF-8">
</head>
<body >
<script type="text/javascript">
	$(function () {
		$('.remaining').each(function () {
			// count 정보 및 count 정보와 관련된 textarea/input 요소를 찾아내서 변수에 저장한다.
			var $maxcount = $('.maxcount', this);
			var $count = $('.count', this);
			var $input = $("#contents");

			// .text()가 문자열을 반환하기에 이 문자를 숫자로 만들기 위해 1을 곱한다.
			var maximumByte = $maxcount.text() * 1;
			// update 함수는 keyup, paste, input 이벤트에서 호출한다.
			var update = function () {
				var before = $count.text() * 1;
				var str_len = $input.val().length;
				var cbyte = 0;
				var li_len = 0;
				for (i = 0; i < str_len; i++) {
					var ls_one_char = $input.val().charAt(i);
					if (escape(ls_one_char).length > 4) {
						cbyte += 2; //한글이면 2를 더한다
					} else {
						cbyte++; //한글아니면 1을 다한다
					}
					if (cbyte <= maximumByte) {
						li_len = i + 1;
					}
				}
				// 사용자가 입력한 값이 제한 값을 초과하는지를 검사한다.
				if (parseInt(cbyte) > parseInt(maximumByte)) {
					alert('허용된 글자수가 초과되었습니다.\r\n\n초과된 부분은 자동으로 삭제됩니다.');
					var str = $input.val();
					var str2 = $input.val().substr(0, li_len);
					$input.val(str2);
					var cbyte = 0;
					for (i = 0; i < $input.val().length; i++) {
						var ls_one_char = $input.val().charAt(i);
						if (escape(ls_one_char).length > 4) {
							cbyte += 2; //한글이면 2를 더한다
						} else {
							cbyte++; //한글아니면 1을 다한다
						}
					}
				}
				$count.text(cbyte);
			};
			// input, keyup, paste 이벤트와 update 함수를 바인드한다
			$input.bind('input keyup keydown paste change', function () {
				setTimeout(update, 0)
			});
			update();
		});
	});
</script>
<div>
<textarea rows="5" cols="50" id="contents"/></textarea>
</div>
<span class="remaining">
	<span class="count">0</span>/<span class="maxcount">80</span>byte(한글 40자, 영어 80자)
</span>
</body>
</html>


댓글()