'Front-End/J-Query'에 해당되는 글 8건

Front-End/J-Query

Jquery 기본 문법

<script>


$(document).ready(function(){


... jQuery 메소드, 액션을 입력 ...


});


</script>




<script>


$(function(){


... jQuery 메서드, 액션을 입력 ...


});


</script>


출처 : http://theqoop.tistory.com/295

'Front-End > J-Query' 카테고리의 다른 글

w3schools - templates  (0) 2017.07.06
jQuery Misc  (0) 2017.07.06
jQuery AJAX  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jquery HTML  (0) 2017.07.06
,
Front-End/J-Query

w3schools - templates

https://www.w3schools.com/w3css/w3css_templates.asp

'Front-End > J-Query' 카테고리의 다른 글

Jquery 기본 문법  (0) 2017.10.23
jQuery Misc  (0) 2017.07.06
jQuery AJAX  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jquery HTML  (0) 2017.07.06
,
Front-End/J-Query

jQuery Misc

다른 자바스크립트 프레임워크와 충돌방지


jQuery - The noConflict() Method


jQuery and Other JavaScript Frameworks


- 앵글러js,백본js,엠버js 등등 사용할때

$표시를 사용하면 j-query 충돌함


The jQuery noConflict() Method 

- js프레임워크 충돌방지


Ex1)
<script>
$.noConflict();
jQuery(document).ready(function(){        // 기존 $ 표시 대신 현재 jQueury
    jQuery("button").click(function(){        // 기존 $ 표시 대신 현재 jQueury
        jQuery("p").text("jQuery is still working!"); // 기존 $ 표시 대신 현재 jQueury
    });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<button>Test jQuery</button>

</body>
</html>
Ex2) - 다른 방법 - 변수로 지정해서 사용
<script>
var jq = $.noConflict();                     // 기존 $에서 현재 변수명 jq = $.noConflict(); 사용
jq(document).ready(function(){            // 변수 jq
    jq("button").click(function(){            // 변수 jq
        jq("p").text("jQuery is still working!");    // 변서 jq
    });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<button>Test jQuery</button>

</body>
</html>
Ex3) - 다른 방법 - 함수 안에서 사용하면됨
<script>
$.noConflict();                                    // $.noConflict(); 지정을 하고
jQuery(document).ready(function($){    // .ready 메소드에 파라미터 ($) 넘겨줌
    $("button").click(function(){
        $("p").text("jQuery is still working!");
    });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<button>Test jQuery</button>

</body>
</html> 


'Front-End > J-Query' 카테고리의 다른 글

Jquery 기본 문법  (0) 2017.10.23
w3schools - templates  (0) 2017.07.06
jQuery AJAX  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jquery HTML  (0) 2017.07.06
,
Front-End/J-Query

jQuery AJAX

jQuery - AJAX Introduction

jQuery AJAX Example - AJAX  서버에서 값 가져오기

What is AJAX?

AJAX = Asynchronous JavaScript and XML.     // 비동기화 한 자바스크립트 그리고 XML
특정 지정된 내용만 불러들이는 기술, 전체를 로드하지 않음
AJAX는 전체 페이지를 다시 로그하지 않고, 백그라운드에서 데이터를 로드하여 웹 페이지에 표시하는 
기능

What About jQuery and AJAX?

jQuery provides several methods for AJAX functionality.
jQuery는 AJAX 기능을 위한 몇 가지 메소드를 제공
jQuery AJAX 메소드를 사용하면 HTTP Get 및 HTTP Post를 사용하여 원격 서버에서 텍스트, HTML, XML 또는 JSON을 요청할 수 있으며 웹페이지의 선택된 HTML 요소에 외부 데이터를 직접 로드 할 수 
있음

jQuery가 없으면 AJAX 코딩이 까다로움

다른 브라우저를 테스트 하기 위해서 추가 코드를 작성해야하는데 jQuery 팀이 이 문제를 처리하여
한줄 코드만으로  AJAX  기능을 작성할수 있음(팩트 폭행)

jQuery - AJAX load() Method

jQuery load() Method

jQuery load() 메서드는 간단하지만 강력한 AJAX 메서드
load() 메서드는 서버에서 데이터를 로드하고 반환 된 데이터를 선택한 요소에 저장

Syntax:
$(selector).load(URL,data,callback);    // (선택자).로드(서버주소,데이터,콜백);

필수 URL 매개 변수는로드하려는 URL을 지정합니다.
선택적 data 매개 변수는 요청과 함께 보낼 쿼리 문자열 키 / 값 쌍의 집합을 지정합니다.
선택적 콜백 매개 변수는 load () 메서드가 완료된 후 실행할 함수의 이름입니다.
예제 파일의 내용은 다음과 같습니다. "demo_test.txt":

demo_test.txt 파일의 내용을 특정 <div> 로드함
Ex)1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt");        // 서버에 있는 txt 내용을 로드함
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

서버에 있는 demo_test.txt 내용 = jQuery and AJAX is FUN!

Ex)2 - 특정 내용만 불러들인다.
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt #p1");    // txt문서에서 id가 p1인 부분만 로드
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>
p1 내용 = <p id="p1">This is some text in a paragraph.</p>

콜백함수 사용
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){    // 콜백함수
            if(statusTxt == "success")            // 문서가 로드가 잘되었으면 success
                alert("External content loaded successfully!");
            if(statusTxt == "error")                // 문서가 로드가 안되었으면 error
                alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

jQuery AJAX Reference

https://www.w3schools.com/jquery/jquery_ref_ajax.asp

jQuery - AJAX get() and post() Methods

HTTP Request: GET vs. POST

  • GET - Requests data from a specified resource                        // 검색결과 url 뒤에 붙음
  • POST - Submits data to be processed to a specified resource   // 비밀번호

jQuery $.get() Method

Syntax:
$.get(URL,callback);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("demo_test.asp", function(data, status){    // 콜백 함수 사용 불러오면 alert
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>

Tip: Here is how the ASP file looks like ("demo_test.asp"):

<%
response.write("This is some text from an external ASP file.")
%>

jQuery $.post() Method

Syntax:

$.post(URL,data,callback);
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.post("demo_test_post.asp",
        {
          name: "Donald Duck",
          city: "Duckburg"
        },
        function(data,status){  // 콜백 함수가 실행 // 콜백은 모든 기능이 끝났을때 기다렸다가 실행
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

Tip: Here is how the ASP file looks like ("demo_test_post.asp"):
<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>

jQuery AJAX Reference

https://www.w3schools.com/jquery/jquery_ref_ajax.asp


'Front-End > J-Query' 카테고리의 다른 글

w3schools - templates  (0) 2017.07.06
jQuery Misc  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jquery HTML  (0) 2017.07.06
jQuery Effects  (0) 2017.07.06
,
Front-End/J-Query

jQuery Traversing

핵심 특정 엘리먼트만 선택한다

jQuery Traversing - 조상으로 이동 상위로

DOM tree 내에서 종횡무진 하기

<div>
<ul>
    <li>                         <li>
<span>    <span>               <b>

Tree 조상 부모 고정 관계에서 
관계를 무시하고 종횡무진 이동할수 있다.

jQuery Traversing Methods

https://www.w3schools.com/jquery/jquery_ref_traversing.asp

jQuery Traversing - Ancestors 

- 조상으로부터 올라감

Traversing Up the DOM Tree

  • parent()         // 부모
  • parents()        // 부모들
  • parentsUntil() // 유틸

jQuery parent() Method - 지정된 부모만 엘리 선택

<style>
.ancestors * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("span").parent().css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body>

<div class="ancestors">
  <div style="width:500px;">div (great-grandparent)
    <ul>ul (grandparent)  
      <li>li (direct parent)
        <span>span</span>
      </li>
    </ul>   
  </div>

  <div style="width:500px;">div (grandparent)   
    <p>p (direct parent)
        <span>span</span>
      </p> 
  </div>
</div>

</body>
</html>

jQuery parents() Method - 지정된 엘리 상위 모두 선택

Ex1)
<style>
.ancestors * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("span").parents().css({"color": "red", "border": "2px solid red"});
});
</script>
</head>

<body class="ancestors">body (great-great-grandparent)
  <div style="width:500px;">div (great-grandparent)
    <ul>ul (grandparent)  
      <li>li (direct parent)
        <span>span</span>
      </li>
    </ul>   
  </div>
</body>

<!-- The outer red border, before the body element, is the html element (also an ancestor) -->
</html>
Ex2) - "ul" 특정부분만 선택
<style>
.ancestors * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("span").parents("ul").css({"color": "red", "border": "2px solid red"});
});
</script>
</head>

<body class="ancestors">body (great-great-grandparent)
  <div style="width:500px;">div (great-grandparent)
    <ul>ul (grandparent)  
      <li>li (direct parent)
        <span>span</span>
      </li>
    </ul>   
  </div>
</body>

</html>
jQuery parentsUntil() Method - 상위 어디까지 지정
<style>
.ancestors * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("span").parentsUntil("div").css({"color": "red", "border": "2px solid red"});
});                        // div 전까지 
</script>
</head>
<body class="ancestors"> body (great-great-grandparent)
  <div style="width:500px;">div (great-grandparent)
    <ul>ul (grandparent)  
      <li>li (direct parent)
        <span>span</span>
      </li>
    </ul>   
  </div>
</body>
</html>
jQuery Traversing - Descendants 
조상으로부터 내려감

Traversing Down the DOM Tree

  • children()
  • find()

jQuery children() Method

Ex1)
<style>
.descendants * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").children().css({"color": "red", "border": "2px solid red"});
});                          // div 부모 기준 .children 자식 모두를 위와 같이 선택
</script>
</script>
</head>
<body>

<div class="descendants" style="width:500px;">div (current element) 
  <p>p (child)
    <span>span (grandchild)</span>     
  </p>
  <p>p (child)
    <span>span (grandchild)</span>
  </p> 
</div>

</body>
</html>
Ex2)
<style>
.descendants * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").children("p.first").css({"color": "red", "border": "2px solid red"});
});                             // p.first 특정 자식만 선택
</script>
</head>
<body>

<div class="descendants" style="width:500px;">div (current element) 
  <p class="first">p (child)
    <span>span (grandchild)</span>     
  </p>
  <p class="second">p (child)
    <span>span (grandchild)</span>
  </p> 
</div>

</body>
</html>

jQuery find() Method - 검색해서 선택

Ex1)
<style>
.descendants * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").find("span").css({"color": "red", "border": "2px solid red"});
});                    // span 찾아서 선택
</script>
</head>
<body>

<div class="descendants" style="width:500px;">div (current element) 
  <p>p (child)
    <span>span (grandchild)</span>     
  </p>
  <p>p (child)
    <span>span (grandchild)</span>
  </p> 
</div>

</body>
</html>
Ex2) 선택한 부모 밑에 자식 모두 선택
<style>
.descendants * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").find("*").css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body>

<div class="descendants" style="width:500px;">div (current element) 
  <p>p (child)
    <span>span (grandchild)</span>     
  </p>
  <p>p (child)
    <span>span (grandchild)</span>
  </p> 
</div>

</body>
</html>

jQuery Traversing - Siblings - 

같은 형제끼리 이동(옆으로 이동)

Traversing Sideways in The DOM Tree

  • siblings()        // 형제끼리 이동
  • next()            // 다음에 오는거
  • nextAll()        // 다음에 오는거 전부
  • nextUntil()     //  다음에 어디까지
  • prev()            // 그전에
  • prevAll()        // 그전에 모두
  • prevUntil()     // 그전에 어디까지

jQuery siblings() Method

Ex1)
<style>
.siblings * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("h2").siblings().css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body class="siblings">

<div>div (parent)        // 한 부모 div  자식
  <p>p</p>
  <span>span</span>
  <h2>h2</h2>
  <h3>h3</h3>
  <p>p</p>
</div>

</body>
</html>
Ex2) - 특정 대상만 선택
<style>
.siblings * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("h2").siblings("p").css({"color": "red", "border": "2px solid red"});
});                                // P만 선택
</script>
</head>
<body class="siblings">

<div>div (parent)
  <p>p</p>
  <span>span</span>
  <h2>h2</h2>
  <h3>h3</h3>
  <p>p</p>
</div>

</body>
</html>

jQuery next() Method - 그 다음꺼만 리턴

<style>
.siblings * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("h2").next().css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body class="siblings">

<div>div (parent)
  <p>p</p>
  <span>span</span>
  <h2>h2</h2>
  <h3>h3</h3>
  <p>p</p>
</div>

</body>
</html>

jQuery nextAll() Method - 그 다음꺼 전부

<style>
.siblings * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("h2").nextAll().css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body class="siblings">

<div>div (parent)
  <p>p</p>
  <span>span</span>
  <h2>h2</h2>
  <h3>h3</h3>
  <p>p</p>
</div>

</body>
</html>

jQuery nextUntil() Method - 사이에꺼만 선택

<style>
.siblings * { 
    display: block;
    border: 2px solid lightgrey;
    color: lightgrey;
    padding: 5px;
    margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("h2").nextUntil("h6").css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body class="siblings">

<div>div (parent)
  <p>p</p>
  <span>span</span>
  <h2>h2</h2>
  <h3>h3</h3>
  <h4>h4</h4>
  <h5>h5</h5>
  <h6>h6</h6>
  <p>p</p>
</div>

</body>
</html>

jQuery prev(), prevAll() & prevUntil() Methods

The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).

jQuery Traversing - Filtering 

- CSS 선택해서 골라서 이동

The first(), last(), eq(), filter() and not() Methods

jQuery first() Method

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").first().css("background-color", "yellow");    // 첫번째 P만 지정
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>This is a paragraph.</p>

<div style="border: 1px solid black;">        // 첫번째 div
  <p>A paragraph in a div.</p>                   //
  <p>Another paragraph in a div.</p>        //
</div>
<br>

<div style="border: 1px solid black;">
  <p>A paragraph in another div.</p>
  <p>Another paragraph in another div.</p>
</div>
<br>

<div style="border: 1px solid black;">
  <p>A paragraph in another div.</p>
  <p>Another paragraph in another div.</p>
</div>

</body>
</html>

jQuery last() Method - 마지막꺼만 선택

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").last().css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>This is a paragraph.</p>

<div style="border: 1px solid black;">
  <p>A paragraph in a div.</p>
  <p>Another paragraph in a div.</p>
</div>
<br>

<div style="border: 1px solid black;">
  <p>A paragraph in another div.</p>
  <p>Another paragraph in another div.</p>
</div>
<br>

<div style="border: 1px solid black;">             // 마지막 div
  <p>A paragraph in another div.</p>             //    
  <p>Another paragraph in another div.</p>  //
</div>

</body>
</html>

jQuery eq() method - 숫자로 선택(0부터 순차적)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").eq(1).css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald (index 0).</p>
<p>Donald Duck (index 1).</p>
<p>I live in Duckburg (index 2).</p>
<p>My best friend is Mickey (index 3).</p>

</body>
</html>

jQuery filter() Method - 필터 : 골라서 본다 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").filter(".intro").css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald.</p>
<p class="intro">I live in Duckburg.</p>
<p class="intro">I love Duckburg.</p>
<p>My best friend is Mickey.</p>

</body>
</html>

jQuery not() Method - 그거 아닌것만 골라

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").not(".intro").css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald.</p>
<p class="intro">I live in Duckburg.</p>
<p class="intro">I love Duckburg.</p>
<p>My best friend is Mickey.</p>

</body>
</html>


'Front-End > J-Query' 카테고리의 다른 글

jQuery Misc  (0) 2017.07.06
jQuery AJAX  (0) 2017.07.06
jquery HTML  (0) 2017.07.06
jQuery Effects  (0) 2017.07.06
jQuery Tutorial  (0) 2017.07.01
,
Front-End/J-Query

jquery HTML

jQuery - Get

jQuery - Get Content and Attributes

제인쿼리에서 문서 객체를 다루는것

jQuery DOM Manipulation

DOM = Document Object Model        // 문서 객체 모델

Get Content - text(), html(), and val() 

속성 요소를 Get 가져온다.

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){                  // btn2 선택자
        alert("Text: " + $("#test").text());    // btn1 선택자 텍스트 문자만 Get 불러온다
    });
    $("#btn2").click(function(){                  // btn2 선택자
        alert("HTML: " + $("#test").html());  // btn2 html body html태그 모두 Get 불러온다
    });
});
</script>
</head>
<body>

<p id="test">This is some <b>bold</b> text in a paragraph.</p>

<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>

</body>
</html>
jQuery val() method - val 변수에 담긴 값 Get
<script>
$(document).ready(function(){
    $("button").click(function(){                // 버튼을 클릭하면
        alert("Value: " + $("#test").val()); // 선택자 "test" val는 입력받은 값 Mickey Mouse 출력
    });                                                      // id="test"에 있는 value 값을 Get = Mickey Mouse
});
</script>
</head>
<body>

<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>

<button>Show Value</button>

</body>
</html>
Get Attributes - attr() - 속성(애트뷰트) 
엘리먼트(요소)
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert($("#w3s").attr("href"));// 하이퍼 레퍼런스(href)속성 값(URL)을 Get 한다
    });
});
</script>
</head>
<body>

<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>

<button>Show href Value</button>

</body>
</html>
jQuery - Set Content and Attribute - 

기존에 있었던거에서 새롭게 셋팅한다.

(Set)

Set Content - text(), html(), and val()

We will use the same three methods from the previous page to set content:

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields

The following example demonstrates how to set content with the jQuery text(), html(), and val() methods:


<script>
$(document).ready(function(){
    $("#btn1").click(function(){           // text
        $("#test1").text("Hello world!"); // 기존 This is a paragraph 에서 현재 Hello world! 변경
    });
    $("#btn2").click(function(){                          // html
        $("#test2").html("<b>Hello world!</b>"); // 기존 : This is 에서 현재 <b>Hello 변경
    });
    $("#btn3").click(function(){           // val
        $("#test3").val("Dolly Duck");    // 기존 : Mickey 현재 : Dolly Duck 변경
    });
});
</script>
</head>
<body>

<p id="test1">This is a paragraph.</p>
<p id="test2">This is another paragraph.</p>

<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>

<button id="btn1">Set Text</button>
<button id="btn2">Set HTML</button>
<button id="btn3">Set Value</button>

</body>
</html>
get 과 set 차이점
get = text(), html(), val() 가져온다
set = text("Hello world"), html("html문서 변수에(소스작성)넣는다"), val(값을 넣는다) 파라미터 값을 직접 넣는다
A Callback Function for text(), html(), and val() - 콜백(function()) 함수
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("#test1").text(function(i, origText){  // 값을 2개 받음 i로 받고 origText 받고 합쳐서 출력
            return "Old text: " + origText + " New text: Hello world! (index: " + i + ")"; 
        });    // Old text 와 New text 합쳐서 출력됨!!!!!! @.@ 어려움
    });
    $("#btn2").click(function(){
        $("#test2").html(function(i, origText){    // 기존 text + newtext 2개 받고 합쳐서 출력
            return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i +     ")"; 
        });    // Old text 와 New text 합쳐서 출력됨!!!!!! @.@ 어려움 
    });
});
</script>
</head>
<body>

<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>

<button id="btn1">Show Old/New Text</button>
<button id="btn2">Show Old/New HTML</button>

</body>
</html>

Set Attributes - attr() - href 속성 변경하기 콜백

Ex)1

<script>

$(document).ready(function(){

    $("button").click(function(){    // 하이퍼 레퍼런스 href 속성 url 변경

        $("#w3s").attr("href", "https://www.w3schools.com/jquery"); //W3Schools 변경   

    });

});

</script>

</head>

<body>

<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>

<button>Change href Value</button>

<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

</body>

</html>

Ex)2
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#w3s").attr({
            "href" : "https://www.w3schools.com/jquery",
            "title" : "W3Schools jQuery Tutorial"
        });
    });
});
</script>
</head>
<body>

<p>
<a href="https://www.w3schools.com" title="some title" ="w3s">W3Schools.com</a></p>

<button>Change href and title</button>

<p>
Mouse over the link to see that the href attribute has changed and a title attribute is set.</p>

</body>
</html>

A Callback Function for attr()

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#w3s").attr("href", function(i, origValue){
            return origValue + "/jquery";     // 기존 href url 끝에 /jquery Set 출력
        });
    }); 
});
</script>
</head>
<body>

<p>
<a href="https://www.w3schools.com" id="w3s">W3Schools.com</a>
</p>

<button>Change href Value</button>
<p>
Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

</body>
</html>

jQuery - Add Elements - 

엘리먼트(컨텐츠) 추가

  • append() - Inserts content at the end of the selected elements // 컨텐츠를 뒷부분에 추가
  • prepend() - Inserts content at the beginning of the selected elements // 앞부분에 추가
  • after() - Inserts content after the selected elements    // 뒷부분 추가
  • before() - Inserts content before the selected elements    // 앞부분 추가

jQuery append() Method - 뒷부분 추가

<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("p").append(" <b>Appended text</b>."); // 기존 텍스트 끝에 추가
    });
    $("#btn2").click(function(){
        $("ol").append("<li>Appended item</li>");  // 기존 텍스트 하단에 컨텐츠 추가
    });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>

<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
</body>
</html>

jQuery prepend() Method - 앞부분에 컨텐츠 추가

<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("p").prepend("<b>Prepended text</b>. ");  // 기존 텍스트 처음에 추가 
    });
    $("#btn2").click(function(){
        $("ol").prepend("<li>Prepended item</li>");   // 기존 텍스트 윗단에 컨텐츠 추가
    });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>

<button id="btn1">Prepend text</button>
<button id="btn2">Prepend list item</button>

</body>
</html>

Add Several New Elements With append() and prepend() - JQuery 에서 새로운 엘리먼트 추가

<script>
function appendText() {                              // 매개변수 추가
    var txt1 = "<p>Text.</p>";                   //  Create text with HTML text 1개 추가
    var txt2 = $("<p></p>").text("Text.");  // Create text with jQuery text 1개 추가
    var txt3 = document.createElement("p");
    txt3.innerHTML = "Text.";                   // Create text with DOM  text 1개 추가
    $("body").append(txt1, txt2, txt3);  // Append new elements <body> Append text  
}                                                         // text 3개 추가
</script>
</head>
<body>

<p>This is a paragraph.</p>

<button onclick="appendText()">Append text</button>

</body>
</html>

jQuery after() and before() Methods

<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("img").before("<b>Before</b>");  // 선택자 img 앞에 before 출력
    });

    $("#btn2").click(function(){
        $("img").after("<i>After</i>");        // 선택자 img 뒤에 After 출력
    });
});
</script>
</head>
<body>
<img src="/images/w3jquery.gif" alt="jQuery" width="100" height="140"><br><br>
<button id="btn1">Insert before</button>
<button id="btn2">Insert after</button>
</body>
</html>

Add Several New Elements With after() and before() - 각각 엘리먼트 속성에 따라 추가하는 방법

<script>
function afterText() {
    var txt1 = "<b>I </b>";                        // Create element with HTML
    var txt2 = $("<i></i>").text("love ");     // Create with jQuery
    var txt3 = document.createElement("b"); // Create with DOM
    txt3.innerHTML = "jQuery!";
    $("img").after(txt1, txt2, txt3);              // Insert new elements after img
}
</script>
</head>
<body>

<img src="/images/w3jquery.gif" alt="jQuery" width="100" height="140">

<p>Click the button to insert text after the image.</p>
<button onclick="afterText()">Insert after</button>

</body>
</html>
jQuery - Remove Elements - 컨텐츠 제거
  • remove() - Removes the selected element (and its child elements)  // 모두 없어짐
  • empty() - Removes the child elements from the selected element    // 자식만 없어짐

jQuery remove() Method - 모두 없어짐

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").remove();        // 선택한 엘리먼트 중 자식 엘리먼트까지 모두 사라짐
    });
});
</script>
</head>
<body>

<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.

<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>

<br>
<button>Remove div element</button>

</body>
</html>

jQuery empty() Method -자식 엘리만 없어짐

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").empty();        // 선택한 자식 엘리먼트만 사라짐
    });
});
</script>
</head>
<body>

<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">

This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>
<br>

<button>Empty the div element</button>

</body>
</html>

Filter the Elements to be Removed - 필더

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").remove(".test");        // test 선택자만 찾아서 사라짐
    });
});
</script>
<style>
.test {
    color: red;
    font-size: 20px;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<p class="test">This is another paragraph.</p>

<button>Remove all p elements with class="test"</button>

</body>
</html>
// 여기서는 test 선택자와 demo 선택자 사라짐
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").remove(".test, .demo");
    });
});
</script>
<style>
.test {
    color: red;
    font-size: 20px;
}

.demo {
    color: green;
    font-size: 25px;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="test">This is p element with class="test".</p>
<p class="test">This is p element with class="test".</p>
<p class="demo">This is p element with class="demo".</p>

<button>Remove all p elements with class="test" and class="demo"</button>

</body>
</html>

jQuery - CSS Classes (CSS 다루기)

jQuery - Get and Set CSS Classes

jQuery Manipulating CSS

  • addClass() - Adds one or more classes to the selected elements        // 지정된 클라스 추가
  • removeClass() - Removes one or more classes from the selected elements    // 지정된 클라스 제거
  • toggleClass() - Toggles between adding/removing classes from the selected elements   
  • // 토글 할때마다 +- 
  • css() - Sets or returns the style attribute    // 속성값 반환

Example Stylesheet

.important {                
    font-weight: bold;
    font-size: xx-large;
}

.blue {
    color: blue;
}
jQuery addClass() Method    - 클라스 추가
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1, h2, p").addClass("blue");    // 선택한 엘리먼트가 블루색으로 변경
        $("div").addClass("important");     // div  글자체가 인포턴트로 변경
    });
});
</script>
<style>
.important {
    font-weight: bold;
    font-size: xx-large;
}
.blue {
    color: blue;
}
</style>
</head>
<body>

<h1>Heading 1</h1>
<h2>Heading 2</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<div>This is some important text!</div><br>

<button>Add classes to elements</button>

</body>
</html>

multiple classes within the addClass() method:
클라스 추가 할때 여러가지를 추가할수 있다
<script>
$(document).ready(function(){
    $("button").click(function(){        // 콜백
        $("#div1").addClass("important blue"); // div1 파라미터를 여러개 지정
    });                                                                   // 글자체 변경 색깔변경
});
</script>
<style>
.important {
    font-weight: bold;
    font-size: xx-large;
}

.blue {
    color: blue;
}
</style>
</head>
<body>

<div id="div1">This is some text.</div>
<div id="div2">This is some text.</div>
<br>

<button>Add classes to first div element</button>

</body>
</html>

jQuery removeClass() Method - 클라스 색깔 제거

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1, h2, p").removeClass("blue");    // blue 색깔 제거
    });
});
</script>
<style>
.important {
    font-weight: bold;
    font-size: xx-large;
}

.blue {
    color: blue;
}
</style>
</head>
<body>

<h1 class="blue">Heading 1</h1>
<h2 class="blue">Heading 2</h2>

<p class="blue">This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Remove class from elements</button>

</body>
</html>

jQuery toggleClass() Method - On Off

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1, h2, p").toggleClass("blue");  // On - 적용 Off - 해제 [클릭할때마다 변경]
    });
});
</script>
<style>
.blue {
    color: blue;
}
</style>
</head>
<body>

<h1>Heading 1</h1>
<h2>Heading 2</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Toggle class</button>

</body>
</html>

CSS 레퍼런스
https://www.w3schools.com/jquery/jquery_ref_html.asp

jQuery - css() Method

하나 이상의 속성값을 반환하거나 변경 

Return a CSS Property - 객체의 속성을 반환(보여)

css("propertyname");
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Background color = " + $("p").css("background-color")); // 첫번째 P(엘리)만
    });                                               // Background color (Property 속성값)= rgb(255, 0, 0)
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<button>Return background-color of p</button>

</body>
</html>
Set a CSS Property - Set 으로 css 변경
css("propertyname","value");
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css("background-color", "yellow");    // P엘리먼트 모두 노란색으로 변경
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set background-color of p</button>

</body>
</html>

Set Multiple CSS Properties - 여러게 엘리 속성 변경

css({"propertyname":"value","propertyname":"value",...});
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css({"background-color": "yellow", "font-size": "200%"});
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set multiple styles for p</button>

</body>
</html>
## CSS 참고 문서
https://www.w3schools.com/jquery/jquery_ref_html.asp
jQuery - Dimensions - 면접 다루기

jQuery Dimension Methods

  • width()
  • height()
  • innerWidth()
  • innerHeight()
  • outerWidth()
  • outerHeight()

jQuery width() and height() Methods - w,h 면적값 반환

<script>

$(document).ready(function(){

    $("button").click(function(){

        var txt = "";

        txt += "Width of div: " + $("#div1").width() + "</br>";

        txt += "Height of div: " + $("#div1").height();

        $("#div1").html(txt);

    });

});

</script>

<style>

#div1 {

    height: 100px;

    width: 300px;

    padding: 10px;

    margin: 3px;

    border: 1px solid blue;

    background-color: lightblue;

}

</style>

</head>

<body>


<div id="div1"></div>

<br>


<button>Display dimensions of div</button>


<p>width() - returns the width of an element.</p>

<p>height() - returns the height of an element.</p>


</body>

</html>

jQuery innerWidth() and innerHeight() Methods

각각 면적 값을 반환
<script>
$(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Width of div: " + $("#div1").width() + "</br>";       
        txt += "Height of div: " + $("#div1").height() + "</br>";
        txt += "Inner width of div: " + $("#div1").innerWidth() + "</br>";
        txt += "Inner height of div: " + $("#div1").innerHeight();
        $("#div1").html(txt);
    });
});
</script>
</head>
<style>
#div1 {
    height: 100px;
    width: 300px;
    padding: 10px;
    margin: 3px;
    border: 1px solid blue;
    background-color: lightblue;
}
</style>
<body>

<div id="div1"></div>
<br>

<button>Display dimensions of div</button>

<p>innerWidth() - returns the width of an element (includes padding).</p>
<p>innerHeight() - returns the height of an element (includes padding).</p>

</body>
</html>

jQuery outerWidth() and outerHeight() Methods

각각 면적 값을 반환
Ex1)
<script>
$(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Width of div: " + $("#div1").width() + "</br>";
        txt += "Height of div: " + $("#div1").height() + "</br>";
        txt += "Outer width of div: " + $("#div1").outerWidth() + "</br>";
        txt += "Outer height of div: " + $("#div1").outerHeight();
        $("#div1").html(txt);
    });
});
</script>
<style>
#div1 {
    height: 100px;
    width: 300px;
    padding: 10px;
    margin: 3px;
    border: 1px solid blue;
    background-color: lightblue;
}
</style>
</head>
<body>

<div id="div1"></div>
<br>

<button>Display dimensions of div</button>

<p>outerWidth() - returns the width of an element (includes padding and border).</p>
<p>outerHeight() - returns the height of an element (includes padding and border).</p>

</body>
</html>
Ex2)
<script>
$(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Width of div: " + $("#div1").width() + "</br>";
        txt += "Height of div: " + $("#div1").height() + "</br>";
        txt += "Outer width of div (margin included): " + $("#div1").outerWidth(true) + "</br>";
        txt += "Outer height of div (margin included): " + $("#div1").outerHeight(true);
        $("#div1").html(txt);
    });
});
</script>
<style>
#div1 {
    height: 100px;
    width: 300px;
    padding: 10px;
    margin: 3px;
    border: 1px solid blue;
    background-color: lightblue;
}
</style>
</head>
<body>

<div id="div1"></div>
<br>

<button>Display dimensions of div</button>

<p>outerWidth(true) - returns the width of an element (includes padding, border, and margin).</p>
<p>outerHeight(true) - returns the height of an element (includes padding, border, and margin).</p>

</body>
</html>

jQuery More width() and height()

Ex1)
<script>
$(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Document width/height: " + $(document).width();
        txt += "x" + $(document).height() + "\n";
        txt += "Window width/height: " + $(window).width();
        txt += "x" + $(window).height();
        alert(txt);
    });
});
</script>
</head>
<body>

<button>Display dimensions of document and window</button>

</body>
</html>
Ex2)
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").width(500).height(500);
    });
});
</script>
<style>
#div1 {
    height: 100px;
    width: 300px;
    padding: 10px;
    margin: 3px;
    border: 1px solid blue;
    background-color: lightblue;
}
</style>
</head>
<body>

<div id="div1"></div>
<br>

<button>Resize div</button>

</body>
</html>


'Front-End > J-Query' 카테고리의 다른 글

jQuery Misc  (0) 2017.07.06
jQuery AJAX  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jQuery Effects  (0) 2017.07.06
jQuery Tutorial  (0) 2017.07.01
,
Front-End/J-Query

jQuery Effects

jQuery Effects - Hide and Show - 효과(이벤트랑 다름)


jQuery hide() and show() - btn 선택 숨김 / btn 선택 보여줌


$("#hide").click(function(){  // 도큐먼트 준비되면
    $("p").hide();            // p태그 선택하면 숨김
});

$("#show").click(function(){  // 도큐맨트 준비되면
    $("p").show();            // p태그 선택 보여줌
});
<button id="hide">Hide</button>
<button id="show">Show</button>

$(selector).hide(speed,callback);    // 숨기는 속도 조절 가능

$(selector).show(speed,callback);    // 보여주는 속도 조절 가능

$("button").click(function(){
    $("p").hide(1000);    // 1000 = 1초
});

jQuery toggle() - 토글

$("button").click(function(){ // btn 클릭
    $("p").toggle();    // 선택자P 클릭하면 보여주고 사라지게 해줌
});
$(selector).toggle(speed,callback);

<button>Toggle between hiding and showing the paragraphs</button>

<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>

$(selector).toggle(speed,callback);    // selector선택자 속도 조절 및 롤백

// 참고 제인쿼리 임펙터 라이브 러리
https://www.w3schools.com/jquery/jquery_ref_effects.asp
!!!가져다 쓰면 된다@@@

jQuery Effects - Fading - 

시각적효과 *

부드럽게 사라지거나 보여주거나 하는 기능


jQuery Fading Methods - 종류

With jQuery you can fade an element in and out of visibility.

jQuery has the following fade methods:

  • fadeIn()
  • fadeOut()
  • fadeToggle()
  • fadeTo()
jQuery fadeIn() Method - 보여짐
$(selector).fadeIn(speed,callback); // 선택자 .메소드명(fadeIn),(속도, 되돌리기)

Ex)
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").fadeIn();            // 기본값으로 페이드인
        $("#div2").fadeIn("slow");   // 느리게
        $("#div3").fadeIn(3000);     // 속도 지정
    });
});
</script>
<div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>

jQuery fadeOut() Method - 사라짐

$(selector).fadeOut(speed,callback);
$("button").click(function(){
    $("#div1").fadeOut();        //사라짐
    $("#div2").fadeOut("slow");  // 느리게 옵션
    $("#div3").fadeOut(3000);    // 속도 지정    3000은 3초
});
<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

jQuery fadeToggle() Method - 클릭에 따라 On Off

$(selector).fadeToggle(speed,callback);

$("button").click(function(){
    $("#div1").fadeToggle();        // On Off
    $("#div2").fadeToggle("slow");    // 느리게
    $("#div3").fadeToggle(3000);    //속도 지정
});
<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

jQuery fadeTo() Method - 투명도

$(selector).fadeTo(speed,opacity,callback); // opacity 투명도 0으로 갈수록 투명 (0과1지정)
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").fadeTo("slow", 0.15);   // 투명도
        $("#div2").fadeTo("slow", 0.4);    // 투명도
        $("#div3").fadeTo("slow", 0.7);    //투명도
    });
});
</script>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>
jQuery Effects - Sliding - 줄 내림

jQuery Sliding Methods - 종류

  • slideDown()
  • slideUp()
  • slideToggle()

jQuery slideDown() Method

$(selector).slideDown(speed,callback);
<script> 
$(document).ready(function(){
    $("#flip").click(function(){        // 선택자 #flip
        $("#panel").slideDown("slow");  // 선택자 panel
    });
});
</script>
<style> 
#panel, #flip {
    padding: 5px;
    text-align: center;
    background-color: #e5eecc;
    border: solid 1px #c3c3c3;
}

#panel {
    padding: 50px;       
    display: none;    // 디스플레이 안보이게 css 지정
}
</style>
<div id="flip">Click to slide down panel</div>    // 클릭하면
<div id="panel">Hello world!</div>                   // 패널 내려와~~~

jQuery slideUp() Method - 줄 올림

$(selector).slideUp(speed,callback);
<script> 
$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideUp("slow");
    });
});
</script>
<style> 
#panel, #flip {
    padding: 5px;
    text-align: center;
    background-color: #e5eecc;
    border: solid 1px #c3c3c3;
}

#panel {
    padding: 50px;
}
</style>
</head>
<body> 
<div id="flip">Click to slide up panel</div>
<div id="panel">Hello world!</div>
</body>
</html>

jQuery slideToggle() Method - On Off

$(selector).slideToggle(speed,callback);
<script> 
$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideToggle("slow");
    });
});
</script>

<style> 
#panel, #flip {
    padding: 5px;
    text-align: center;
    background-color: #e5eecc;
    border: solid 1px #c3c3c3;
}

#panel {
    padding: 50px;
    display: none;
}
</style>
</head>
<body> 
<div id="flip">Click to slide the panel down or up</div>
<div id="panel">Hello world!</div>
</body>
</html>

jQuery Effects - Animation 

애니메이션

jQuery Animations - The animate() Method

Systex
$(selector).animate({params},speed,callback);
<script> 
$(document).ready(function(){
    $("button").click(function(){         //btn을 클릭하면    // 파라메타
        $("div").animate({left: '250px'});// div선택자를.animate({left:'250px'})이동
    });
});
</script> 
</head>
<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>
</html>
jQuery animate() - Manipulate Multiple Properties - 여러가지를 속성값 준다
<script> 
$(document).ready(function(){
    $("button").click(function(){    
        $("div").animate({
            left: '250px',    // 왼쪽으로
            opacity: '0.5,    // 투명도
            height: '150px',  // 높이
            width: '150px'    // 넓이
        });
    });
});
</script> 
</head>
<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
jQuery animate() - Using Relative Values 상대적으로 
값 지정
This is done by putting += or -= in front of the value:    // 상대적으로 + 주고 - 준다
<script> 
$(document).ready(function(){
    $("button").click(function(){
        $("div").animate({
            left: '250px',           // 상대적으로 값 지정
            height: '+=150px',  // 상대적으로 값 지정
            width: '+=150px'    // 상대적으로 값 지정
        });
    });
});
</script> 
</head>
<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>
</html>

jQuery animate() - Using Pre-defined Values - 사전에 정의된 벨루값을 줄수있다

<script> 
$(document).ready(function(){
    $("button").click(function(){
        $("div").animate({        // 애니메이터
            height: 'toggle'      // 높가 토글값으로 On Off 한다
        });
    });
});
</script> 
</head>
<body>

<p>Click the button multiple times to toggle the animation.</p>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>
</html>

jQuery animate() - Uses Queue Functionality - 애니메이션 연결

<script> 
$(document).ready(function(){
    $("button").click(function(){
        var div = $("div");        // 선택자 div를
        div.animate({height: '300px', opacity: '0.4'}, "slow");    // 높이
        div.animate({width: '300px', opacity: '0.8'}, "slow");     // 가로
        div.animate({height: '100px', opacity: '0.4'}, "slow");    // 높이
        div.animate({width: '100px', opacity: '0.8'}, "slow");    // 가로
    });
});
</script> 
</head>
<body>
<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>
</html>
//핵심 : 순서대로 움직인다
애니메이션 연결
<script> 
$(document).ready(function(){
    $("button").click(function(){
        var div = $("div");  
        div.animate({left: '100px'}, "slow");    // 옆으로 움직이고
        div.animate({fontSize: '3em'}, "slow");  // 폰트를 키운다
    });
});
</script> 
</head>
<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div style="background:#98bf21;height:100px;width:200px;position:absolute;">HELLO</div>

</body>
</html>

jQuery Stop Animations - 효과 중지

jQuery stop() Method - 정지

$(selector).stop(stopAll,goToEnd);    
파라미터 : 모두 정지, goToEnd 
기본 파라미터 : false

<script> 
$(document).ready(function(){
    $("#flip").click(function(){      //선택자 flip 클릭하면
        $("#panel").slideDown(5000);  //panel.slideDown(5초 동안 내려온다)
    });
    $("#stop").click(function(){      // stop 클릭하면
        $("#panel").stop();           // 정지한다.
    });
});
</script>
 
<style> 
#panel, #flip {
    padding: 5px;
    font-size: 18px;
    text-align: center;
    background-color: #555;
    color: white;
    border: solid 1px #666;
    border-radius: 3px;
}

#panel {
    padding: 50px;
    display: none;
}
</style>
</head>
<body>
 
<button id="stop">Stop sliding</button>

<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>

</body>
</html>

jQuery Callback Functions - 효과가 끝났을때 실행되게 하는거

jQuery Callback Functions

다 숨겨지고 나서 다음줄 실행하는 방법이 Callback
모두 사라지고 나서 alert 뛰움
Example with Callback
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").hide("slow", function(){    // 콜백 사용 방법 function() 작성 {} 한줄 끝나고 한줄 시작          alert("The paragraph is now hidden");
        });
    });
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</body>
</html>

이건 다 사라기지 전에 alert 뛰움
Example without Callback
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").hide(1000);                    // 콜백 없음
        alert("The paragraph is now hidden");
    });
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</body>
</html>

jQuery - Chaining - 명령어를 여러개 연결해서 사용

jQuery Method Chaining
<script>
$(document).ready(function(){
    $("button").click(function(){        // (function() 콜백
        $("#p1").css("color", "red").slideUp(2000).slideDown(2000);    // 명령어 묶음
    });
});
</script>
</head>
<body>

<p id="p1">jQuery is fun!!</p>

<button>Click me</button>

</body>
</html>

문법이 엄격하지 않아 한줄 한줄 라인으로 씀
<script>
$(document).ready(function(){
    $("button").click(function(){     // (function() 콜백 명령어가 끝날때까지 기다린다
        $("#p1").css("color", "red")  // 라인
            .slideUp(2000)            // 라인
            .slideDown(2000);         // 라인
    });
});
</script>
</head>
<body>
<p id="p1">jQuery is fun!!</p>
<button>Click me</button>
</body>
</html>


'Front-End > J-Query' 카테고리의 다른 글

jQuery Misc  (0) 2017.07.06
jQuery AJAX  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jquery HTML  (0) 2017.07.06
jQuery Tutorial  (0) 2017.07.01
,
Front-End/J-Query

jQuery Tutorial

JQuery - MOME


JQuery 는 JavaScritp 라이브 러리


JQuery - 적게 쓰고 자바스크립트 효과를 낸다


"Try it Yourself" Examples in Each Chapter - 제이쿼리 실행


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").click(function(){
        $(this).hide();
    });
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

jQuery Introduction

  • HTML
  • CSS
  • JavaScript

What is jQuery? - jQuery 기능

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

Why jQuery?

적게쓰고 자바스크립트 효과를 낸다.
심플하고 강력하다.
많은 회사들이 jQuery 지원한다.

jQuery Get Started - 실행방법

Adding jQuery to Your Web Pages

  • Download the jQuery library from jQuery.com
  • Include jQuery from a CDN, like Google
* CDN 컨텐츠 딜리버리 네트워크 가장 가까운 네트워크에 연결해서 속도를 높인다.

Downloading jQuery - 다운로드 방법

사용방법

html 문서 내 <head>태그 안에 j-query src= 경로 작성

<head>

<script src="jquery-3.2.1.min.js">


</script>

</head>


기존

Do you wonder why we do not have type="text/javascript" inside the <script> tag?

text 사라진 이유??

html5 는 기본 디폴트 랭기지가 자바스크립트라서 text/javascript 없어도됨

참고 바람~

사용법 html <head> 태그에 주소 한줄 넣어주면 됨

jQuery CDN

구글

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">


</script>

</head>


MS

<head>
   <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">


</script>

</head>

jQuery Syntax - 문법

jQuery Syntax

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)

Examples:

$(selector).action() // 준비

// 액션

$(this).hide() - hides the current element.        // html 엘리먼트 현재 선택자

$("p").hide() - hides all <p> elements.            // html p 태그 선택

$(".test").hide() - hides all elements with class="test". // 클래스

$("#test").hide() - hides the element with id="test".   // 아이디 지정


제이쿼리 준비

$(document).ready(function(){

   // jQuery methods go here...

});


The Document Ready Event - 이벤트 준비

$(document).ready(function(){        // 준비가 되어야 실행이되고 액션을 실행

   // jQuery methods go here...

});

jQuery Selectors

The element Selector - html 선택자 선택 방법

$("p")    // html 태그 제어


<!DOCTYPE html>   // doctype을 html 지정

<html>            

<head>            // 헤드 태그 사이에 cdn 로딩

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>

$(document).ready(function(){        // document 가 로딩되었는지 확인

    $("button").click(function(){    // 버튼을 클릭했을때 펑션 작동

        $("p").hide();               // btn 클릭했을때 p 태그가 히든 됨

    });

});

</script>

</head>

<body>


<h2>This is a heading</h2>


<p>This is a paragraph.</p>

<p>This is another paragraph.</p>


<button>Click me to hide paragraphs</button>


</body>

</html>

The #id Selector - html id 선택자

$("#test")
<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

    $("button").click(function(){

        $("#test").hide();

    });

});

</script>

</head>

<body>


<h2>This is a heading</h2>


<p>This is a paragraph.</p>

<p id="test">This is another paragraph.</p>


<button>Click me</button>


</body>

</html>

The .class Selector - html class 선택자

$(".test")

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".test").hide();        // html 내 클라스 선택
    });
});
</script>
</head>
<body>

<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me</button>

</body>
</html>

그외

More Examples of jQuery Selectors 방법

SyntaxDescriptionExample
$("*")Selects all elementsTry it
$(this)Selects the current HTML elementTry it
$("p.intro")Selects all <p> elements with class="intro"Try it
$("p:first")Selects the first <p> elementTry it
$("ul li:first")Selects the first <li> element of the first <ul>Try it
$("ul li:first-child")Selects the first <li> element of every <ul>Try it
$("[href]")Selects all elements with an href attributeTry it
$("a[target='_blank']")Selects all <a> elements with a target attribute value equal to "_blank"Try it
$("a[target!='_blank']")Selects all <a> elements with a target attribute value NOT equal to "_blank"Try it
$(":button")Selects all <button> elements and <input> elements of type="button"Try it
$("tr:even")Selects all even <tr> elementsTry it
$("tr:odd")Selects all odd <tr> elements
해설 
$("*") 전부 모두 선택한다.

$(this) 현재 그것을 선택한 그 자체 즉 선택한다.

$("p.intro") P태그 안에 클래스 이름이 intro 선택한다.


$("p:first") 처음 P태그만 선택한다.(여러가지 P태그중에 첫번째꺼만 선택)


$("ul li:first") ul에 li 중에 첫번째 한개만 선택한다.(ul 태그 안에 li태그중에 첫번째꺼만 선택) - 한개만


$("ul li:first-child") ul에서 첫번째 모두 li개수만큼 선택한다.(ul태그 안에 li태그 모두 선택) - li 모두


$("[href]") href 하이퍼 레퍼런스 모두 선택 href="http://www.w3school.com"


$("a[target='blank']") <p><a href="https://www.w3schools.com/html/" target="_blank">HTML Tutorial</a></p> 만 선택한다.


$("a[target!='blank']") != 부정연산자 target='blank 아닌것만 선택한다.


$(":button") 모든 버튼을 선택한다.


$("tr:even") tr태그 even 짝수 즉! 테이블 태그에서 짝수줄만 선택한다. 


$("tr:odd") tr태그에서 odd 홀수 즉! 테이블 태그에서 홀수줄만 선택한다.


Functions In a Separate File 외부파일 불러오기

<head>
   <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
   

</script>
<script src="my_jquery_functions.js">


</script>

</head>


제이쿼리 핵심 이벤트

j-Query Event Methods

Mouse EventsKeyboard EventsForm EventsDocument/Window Events
clickkeypresssubmitload
dblclickkeydownchangeresize
mouseenterkeyupfocusscroll
mouseleave blurunload

jQuery Syntax For Event Methods

$("p").click();    // p 선택자 .click(); 이벤트 = 선택자 + 이벤트      

$("p").click(function(){
  // action goes here!!
});

Commonly Used jQuery Event Methods

$(document).ready()    // 제인쿼리 로딩 및 준비

click() 이벤트 사용법

$("p").click(function(){   // p태그 선택자 이벤트 클릭하면
    $(this).hide();        // this = all 지금 hide 숨김
});


dblclick() 더블클릭 이벤트 사용법 

$("p").dblclick(function(){ // dblclick 이벤트 메소드
    $(this).hide();         // 더블클릭하는 선택자(객체) 그것을 this
});

mouseenter() 마우스 엔터 사용법
$("#p1").mouseenter(function(){  // html id가 p1 선택하고
    alert("You entered p1!");    // mouseenter 마우스를 가져가면 alert("msg출력");
});
<p id="p1">Enter this paragraph.</p>

mouseleave() 마우스 떠나면 - 리브
$("#p1").mouseleave(function(){    // html id가 p1 선택하고
    alert("Bye! You now leave p1!");// mouseleave 마우스를 때면 alert("msg출력");
});
<p id="p1">This is a paragraph.</p>

mousedown() - 마우스버튼을 클릭하면은
$("#p1").mousedown(function(){
    alert("Mouse down over p1!"); // 마우스를 다운하면 alert 안에 msg 출력 ~
});
<p id="p1">This is a paragraph.</p>

mouseup() - 마우스 버튼 업 하면
$("#p1").mouseup(function(){
    alert("Mouse up over p1!");    // 마우스를 업하면 alert 안에 msg 출력~
});
<p id="p1">This is a paragraph.</p>


The on() Method

EX)1
<script>
$(document).ready(function(){
    $("p").on("click", function(){
        $(this).hide();
    });
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>
EX)2
<script>
$(document).ready(function(){
    $("p").on({
        mouseenter: function(){
            $(this).css("background-color", "lightgray");
        },  
        mouseleave: function(){
            $(this).css("background-color", "lightblue");
        }, 
        click: function(){
            $(this).css("background-color", "yellow");
        }  
    });
});
</script>
</head>
<body>

<p>Click or move the mouse pointer over this paragraph.</p>

</body>
</html>

참고

https://www.w3schools.com/jquery/jquery_events.asp


제인쿼리 이벤트 레퍼런스 그때 그때 참고해서 사용하면됨

https://www.w3schools.com/jquery/jquery_ref_events.asp


'Front-End > J-Query' 카테고리의 다른 글

jQuery Misc  (0) 2017.07.06
jQuery AJAX  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jquery HTML  (0) 2017.07.06
jQuery Effects  (0) 2017.07.06
,
  [ 1 ]  

최근 댓글

최근 트랙백

알림

이 블로그는 구글에서 제공한 크롬에 최적화 되어있고, 네이버에서 제공한 나눔글꼴이 적용되어 있습니다.

태그

카운터

Today :
Yesterday :
Total :