Search Results for '개발노트/Script/CSS/jQuery'

18 POSTS

  1. 2012.06.01 jQuery 를 이용해서 div 팝업창 위치 조정하여 뛰우기 4
  2. 2010.05.07 Javascript 단순화의 백미 jQuery
  3. 2010.04.23 자바스크립트 객체 기초

언제부턴가 팝업창이 윈도우 팝업이 아닌 div 팝업이 대세가 되버렸다.

아마도 xp 팝업창 차단기능이 추가되면서부턴가 아닌가 싶다.

 

고객의 요청으로 사이트에 div 팝업을 띄워달라는 요청이 들어왔다.

창 크기에 상관없이 center를 기준으로 왼쪽 100px, top 은 90px 이다.

 

팝업창 기능이야 가장 일반적인것이다. 닫기 버튼과 하루동안 보이지 않기 체크박스

최근 가장 많이 쓰이고 있는(?) jQuery를 이용하여 위의 요구사항을 반영해보았다.

 

1. div 를 페이지 맨 하단에 추가한다.

<div style="position:absolute; width:474px;left:50%; margin-left:-208px; top:40px; z-index:3; display:none" id="layer_pop">

<table> 중략

</table>

 <input type="checkbox" name="today_no" id="today_no" value="1">하루동안 보이지 않기
 <a href="javascript:pop_close();">닫기</a>

</div> 

 

처음은 일단 display:none 으로 추가한다.

 

2. javascript를 추가한다. jQuery용 최신 라이브러리를 import한다.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

 

3. 닫기 버튼 클릭에 대한 구현.

function pop_close() {
        $("#layer_pop").hide(); // 반대는 당연히 show();

}

 

4. onLoad시 hide되어 있는 div 를 show()로 변경하는 스크립트 추가

window.onload = function(){

$("#layer_pop").show();

}

 

5. cookie를 이용하여 "하루동안 보이지 않기" 기능 구현

먼저 getCookie, setCookie를 구현// 워낙 많이 사용한 코드들이므로 쉽게 검색해서 찾아올수 있다.

function getCookie( name ){
 var nameOfCookie = name + "=";
 var x = 0;
 while ( x <= document.cookie.length ) {
  var y = (x+nameOfCookie.length);
  if ( document.cookie.substring( x, y ) == nameOfCookie ) {
   if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
    endOfCookie = document.cookie.length;
   return unescape( document.cookie.substring( y, endOfCookie ) );
  }
  x = document.cookie.indexOf( " ", x ) + 1;
  if ( x == 0 )
   break;
 }
 return "";
}

 

 

function setCookie(name, value, expirehours, domain)  {
        var today = new Date();
        today.setTime(today.getTime() + (60*60*1000*expirehours));
        document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + today.toGMTString() + ";";
        if (domain) {
            document.cookie += "domain=" + domain + ";";
        }

 

닫기 버튼 클릭시 체크박스에 체크가 되어 있는지 여부를 확인한다.

앞에서 구현한 pop_close 함수에 체크박스 확인하는 부분, 쿠키에 값을 넣는 부분을 추가한다.

function pop_close() {
  if($("#today_no").attr("checked")){
      setCookie("layer_pop", "done" , 24);
  }
   $("#layer_pop").hide();    
}

 

6. 이제 마지막으로 onload시 쿠키를 읽어 div 를 show() 할것인가를 확인하면 된다.

window.onload = function(){

if(getCookie('layer_pop') != 'done'){ 

$("#layer_pop").show();

}

}

 

7. 끝? 아니다. div의 위치를 잡아주어야 한다. center를 기준으로 좌측100px 이다. 상단은90px

모니터의 해상도가 아닌 브라우저의 사이즈를 알아와야 한다.

var winwidth=document.all?document.body.clientWidth:window.innerWidth; // 브라우저 가로폭 사이즈 가져오기

// 브라우저 가운데에서 왼쪽으로 100px 이동- 보여지는 div의 가로폭의 1/2 만큼 추가로 빼야한다. 

var left = winwidth/2 - (380/2 + 100);

//브라우저가 작을경우 팝업창이 잘리지 않게 하기 위해서 left 최소값은 팝업창 1/2 로 한다.
if(left < 190) left = 190;

var top = 90;

 

$("div#layer_pop").css({"left":left+"px"});
$("div#layer_pop").css({"top":top+"px"});

 

 

8. 구현된 완성코드를 보면 다음과 같다.

function pop_open(){
  if(getCookie('layer_pop') != 'done'){
       var winwidth=document.all?document.body.clientWidth:window.innerWidth;  
  
      var left = winwidth/2 - 320;// - (380/2 + 100);
      if(left < 190) left = 190;
  
      var top = 90;//windowHeight/2;
        $("div#layer_pop").css({"left":left+"px"});
        $("div#layer_pop").css({"top":top+"px"});
        $("div#layer_pop").show("fast");
     }
 }
  
 window.onload = pop_open;
 window.onresize = pop_open;

 

 

마지막의 window.onresize는 창 키기가 변경될 경우 위치를 변경해 주기 위해서 적용하였다.

 

P.S ==> 플래시영역과 div 팝업이 겹치는 경우 플래시가 div 위로 올라와 버리는 경우가 발생한다.

이런경우 flash의 wmode가 transparent인 경우 z-index 값 많으로 적용이 되지 않는다.

반드시 Opaque로 바꿔주고 z-index를 변경해서 div 팝업이 맨 위로 올라오도록 해야한다.

 

<object  ...

<param name='wmode' value='Opaque' />
<embed wmode='Opaque' ...  />

</object>

 

 

이상 jQuery를 이용한 div 팝업 위치조정하기 편 끝.

마지막 resize 가 속도에 영향을 미치는지에 대한 부분은 ...???

 



Javascript 단순화의 백미 jQuery

Posted 2010. 5. 7. 03:23
jQuery는 복잡한 코드를 간결하게 표현하는 독특한 철학이 있다. 무엇이든 단순하고 재사용 가능한 것으로 유지하기 위해 디자인 되었다. jQuery는 2006년 초 John Resig에 의해 만들어 졌다. DOM 스크립팅과 Ajax의 복잡성을 심플하게 하고 싶다면 jQuery를 권장한다.

다음은 jQuery없는 DOM스크립팅이 얼마나 간결하게 변경되는 보여주는 예제이다.
var external_links = document.getElementById('external_links');var links = external_links.getElementsByTagName('a');for (var i=0;i < links.length;i++) {    var link = links.item(i);    link.onclick = function() {        return confirm('You are going to visit: ' + this.href);    };}이 소스가 아래와 같이 간결해진다.
$('#external_links a').click(function() { return confirm('You are going to visit: ' + this.href);});

window.onload = function() {    // do this stuff when the page is done loading};대신에 
$(window).load(function() {    // run this when the whole page has been downloaded});와 같이 사용이 가능하다.
load와 ready 의 차이
load는 모든 html구성요소의 로딩이 완료될때까지 기다리는 반면 ready는 선택적으로 먼저 로딩을 시킬수가 있다. 
예를 들어 html이 로딩되기 전에 이미지를 먼저 로딩시키고자 한다면 ready를 사용한다.
 $(document).ready(function() {
   // do this stuff when the HTML is all ready
});

이 코드는 document 엘리먼트 주위에 jQuery객체를 만들고 HTML DOM문서가 준비될때 함수를 설정하여 인스턴스를 호출한다.
이 함수를 필요한 만큼 호출한다. 진정한 jQuery 스타일에서, 지름길은 이 함수를 호출하는 것이다. 함수를 $() 함수로 전달한다.

또다를 jQuery의 장점은 스트링을 이용하여 엘리먼트를 생성하는 것이다. 결과는, 그 엘리먼트를 포함하고 있는 jQuery 객체가 된다.
 $('<p></p>')
    .html('Hey World!')
    .css('background', 'yellow')
    .appendTo("body")

$('#message').css('background', 'yellow').html('Hello!').show();

특정 엘리먼트에 Ajax업데이트하기
$('#status').load('status.jsp');


 $.post('save.cgi', {
    text: 'my string',
    number: 23
}, function() {
    alert('Your data has been saved.');
});
==> 매개변수를 서버상의 페이지로 전달할때 사용법

복잡한 Ajax 스크립팅을 사용하는 예제
 $.ajax({
    url: 'document.xml',
    type: 'GET',
    dataType: 'xml',  //xml, html, script, json 으로 지정가능
    timeout: 1000,
    error: function(){  //beforeSend, error, success, complete 콜백 지정가능
        alert('Error loading XML document');
    },
    success: function(xml){
        // do something with xml
    }
});

animate함수를 이용해서 애니메이션을 나타낼수 있다.
$('#groe').animate({height:500,width:500},"slow",function(){
alert('The element is done growing');
}
기본적인 빌트인 함수로 fadeIn, fadeOut, slideDown, slideUp을 사용하여 애니메이션 효과를 나타낼 수 있다.
$('#nav').slideDown('slow');

jQuery는 DOM스크립팅과 이벤트 핸들러를 단순화 하는데 제격이다. DOM의 트래버스와 조작이 쉽고, 이벤트의 첨부, 제거, 호출은 매우 자연스러운 일이며 직접 수행하는 것보다도 에러도 적게 발생한다.
* append() : 다른 엘리먼트로 연결가능
* clone() : 엘리먼트를 중복시킴
* html() :
* empty() : 콘텐츠 삭제
* remove() : 엘리먼트 삭제
* wrap() : 다른 엘리먼트로 엘리먼트를 랩핑한다
 
DOM을 트래버스 함으로써 jQuery 객체의 콘텐츠를 변경할 때 여러 함수를 사용할 수 있다. 엘리먼트의 siblings(), parents(), children()을 사용가능하며 , next(), prev() 엘리먼트도 선택가능하다. 아마도 가장 강력한 것은find()함수 일 것이다. jQuery셀렉터를 사용하며 ,jQuery객체의  엘리먼트 종속관계들을 통해 검색할 수 있다. 이 함수는 end()함수와 사용될 때 더욱 강력해진다. 이 함수는 실행 취소 함수와 비슷하고, find()또는 parents()또는 다른 트래버싱 함수들을 호출하기 전에 가졌던 jQuery객체로 돌아간다.
메소드 체인과 함께 사용되면, 복잡한 연산도 단순하게 보이게 할수 있다.
$('form#login')    // hide all the labels inside the form with the 'optional' class    .find('label.optional').hide().end()    // add a red border to any password fields in the form    .find('input:password').css('border', '1px solid red').end()    // add a submit handler to the form    .submit(function(){        return confirm('Are you sure you want to submit?');    });
위의 코드에서 주석을 제거하면 아래의 형태와 같아진다.
$('form#login').find('label.optional').hide().end().find('input:password').css('border', '1px solid red').end().submit(function(){        return confirm('Are you sure you want to submit?');    });

jQuery의 셀렉터 신택스는 CSS3과 XPath( 하나의 문서에서 엘리먼트를 찾는 강력한 신택스)에 기반하고 있다. CSS3과 XPath 신택스를 더욱 잘 안다면, jQuery 사용이 더욱 수월해진다.
$('td:empty').html('-'); - 테이블의 모든 빈 컬럼안에 대시(dash)를 추가한다.
$('input:not(.required)').hide(); - 'required'클래스를 갖고 있지 않는 input을 숨김
$('ul, ol, dl').hide(); - 다중 셀렉터를 콤마를 이용해서 연결가능.
$("input:checkbox/..").css('border', '1px solid #777'); - 보더를 모든 체크박스의 부모엘리먼트에 추가하려면 /..를 사용.
$('table.striped > tr:odd').css('background', '#999999'); - 보통 가독성 있는 테이블을 나타내기 위해 홀수, 짝수 서로 다른 css를 입히고자 할때..
 
플로그인으로 jQuery확장하기
 
 
===이하는 계속 작성중.... 


자바스크립트 객체 기초

Posted 2010. 4. 23. 17:42
var ride = new Object();
ride.make = 'Yamaha'; -------------- 가
ride.year = 2005;
ride.purchased = new Date(2005,3,12);

var owner = new Object();
owner.name = 'Mr Kim';
owner.job = '백수';
ride.owner = owner;

var ownerName = ride.owner.name;

위의 '가' 는 다음과 같이 정의해도 된다.
ride['make'] = 'Yamaha';
var make = 'make';
ride[make] = 'Yamaha';


위의 내용을 JSon형태로 정의하면 다음과 같다.

var ride = {
  make : 'Yamaha',
  year : 2005,
  purchased :new Date(2005,3,12),
  owner : {
    name : 'Mr Kim',
    job : '백수';
  }
};


1.var foo = bar;
2.window.foo = bar;
3.foo = bar;
위의 1,2,3은 모두 동일.




« PREV : 1 : 2 : 3 : 4 : 5 : 6 : NEXT »