728x90

2076

580

I have this input element:

<input type="text" class="textfield" value="" id="subject" name="subject">

Then I have some other elements, like other text inputs, textareas, etc.

When the user clicks on that input with #subject, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.

The last item of the page is a submit button with #submit:

<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">

The animation should not be too fast and should be fluid.

I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.

javascript jquery

shareimprove this question

edited Sep 26 '17 at 12:18

Maistrenko Vitalii

9441613

asked Jul 13 '11 at 9:49

DiegoP.

18.6k2881100

add a comment

28 Answers

activeoldestvotes

3739

 

Assuming you have a button with the id button, try this example:

$("#button").click(function() { $([document.documentElement, document.body]).animate({ scrollTop: $("#elementtoScrollToID").offset().top }, 2000); });

I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.

<html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script> $(document).ready(function (){ $("#click").click(function (){ $('html, body').animate({ scrollTop: $("#div1").offset().top }, 2000); }); }); </script> <div id="div1" style="height: 1000px; width 100px"> Test </div> <br/> <div id="div2" style="height: 1000px; width 100px"> Test 2 </div> <button id="click">Click me</button> </html>

 Run code snippet

Expand snippet

shareimprove this answer

edited Jul 8 '18 at 14:48

php_nub_qq

7,350144397

answered Jul 13 '11 at 9:52

Steve

42k42637

  • 21

    This will not work in all cases. See stackoverflow.com/questions/2905867/… – Jānis Elmeris Apr 25 '12 at 14:43

  • 6

    @BarryChapman not exactly. After googling I've found this, so both tags are needed if you don't want to have extra logic per browser type. – s3m3n May 10 '13 at 0:01 

  • 69

    If you don't want animation, and instead want to jump instantly to the element, use .scrollTop(…) instead of .animate({scrollTop: …}, …). – Rory O'Kane Sep 20 '13 at 19:53 

  • 9

    In addition to you're solution (which works great), you can add an on complete function that adds the hashtag to the url. In this case it won't scroll, because the scrollTo already scrolled to the right position, and if a user copies the URL it will automatically snap to the right place on the page. – Sander Jan 23 '14 at 8:09

  • 7

    if you use a callback to run when the animation is complete and notice the callback fires twice with this solution, try using "$('html body').animate(..." instead of "$('html, body').animate(..." the comma created two animate events. one for html, one for body. you really just want one for the html body Thanks @T.J. Crowder stackoverflow.com/questions/8790752/… – BoatCode Mar 20 '15 at 16:17 

show 19 more comments

728x90

.children( [ selector ] ) 함수는 필터된 선택자와 일치하는 요소들 각각의 자식 요소들을 가져올 수 있습니다.

원문 링크  http://api.jquery.com/children/

.children( [ selector ] )Returns: jQuery

  • .children( [ selector ] )
  • selector 일치하는 요소들 중에서 추가적으로 선택할 수 있는 선택자 문자열

jQuery 객체는 DOM 요소들의 집합으로 표현됩니다. .children()함수는 DOM 트리에서 자식 요소들을 즉시 찾을 수 있도록 해주고 일치되는 요소들을 새로운 jQuery 객체로 만들어 줍니다. .find()와 .children()함수는 아주 유사하지만 DOM 트리에서 레벨 1의 위치- 첫번째 깊이-만 검색을 하는 부분에서 차이점이 있습니다. 이 부분을 부연설명을 하면, find()함수는 선택요소의 내부 요소들을 모두 검색하고 children()함수는 바라 아래 수준의 요소만 자식요소로 인정한다는 겁니다. 할아버지의 자식은 아버지지 손자가 아니잖아요 ^^;;. 또한 대부분의 jQuery 함수들이 그러하듯이 .children()함수도 text나 주석(comment)들은 반환하지 않습니다. 만약 텍스트 노드나 주석 요소도 반환받고 싶으시면 .contains()함수를 사용하셔야 합니다.

이 함수에는 $() 함수에 인자로 올 수 있는 표현들을 인자로 사용할 수 있습니다. 만약 이 함수에 인자를 사용하게 되면, 그 선택자에 맞게 한번 더 필터 효과를 사용할 수 있게 됩니다.

리스트를 구성하는 마크업을 예로 보시죠.

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

위의 마크업 구조에서 우리는 level-2에서 자식요소를 찾는다고 가정해 보겠습니다. 아래와 같은 스크립트가 필요하겠죠?

$('ul.level-2').children().css('background-color', 'red');

이 스크립트의 결과는 A, B, C 아이템의 배경색을 빨간색으로 변하게 합니다.(find 함수는 level-3에 있는 요소까지 다 가져오겠죠.) children 함수에 인자를 사용하지 않아서 자식 요소들이 모두 선택이 되었지만, 일치하는 아이템을 찾기위해 인자를 사용하면 위의 세 아이템 중 조건에 맞는 요소만 찾게 됩니다.

예 제  
클릭한 요소의 자식 요소들을 찾아서 효과를 줍니다. (빨간 테두리를 입히고 자식 요소의 개수를 아래에 표시해 주네요.)

<!DOCTYPE html>
<html>
<head>
  <style>
  body { font-size:16px; font-weight:bolder; }
  div { width:130px; height:82px; margin:10px; float:left;
        border:1px solid blue; padding:4px; }
  #container { width:auto; height:105px; margin:0; float:none;
        border:none; }
  .hilite { border-color:red; }
  #results { display:block; color:red; }
  p { margin:10px; border:1px solid transparent; }
  span { color:blue; border:1px solid transparent; }
  input { width:100px; }
  em { border:1px solid transparent; }
  a { border:1px solid transparent; }
  b { border:1px solid transparent; }
  button { border:1px solid transparent; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <div id="container">

    <div>
      <p>This <span>is the <em>way</em> we</span> 
      write <em>the</em> demo,</p>

    </div>
    <div>
      <a href="#"><b>w</b>rit<b>e</b></a> the <span>demo,</span> <button>write 
      the</button> demo,
    </div>

    <div>
      This <span>the way we <em>write</em> the <em>demo</em> so</span>

      <input type="text" value="early" /> in
    </div>
    <p>
      <span>t</span>he <span>m</span>orning.
      <span id="results">Found <span>0</span> children in <span>TAG</span>.</span>

    </p>
  </div>
<script>

    $("#container").click(function (e) {
      $("*").removeClass("hilite");
      var $kids = $(e.target).children();
      var len = $kids.addClass("hilite").length;

      $("#results span:first").text(len);
      $("#results span:last").text(e.target.tagName);

      e.preventDefault();
      return false;
    });
</script>

</body>
</html>

미리보기

각 박스 영역을 클릭하시면 자식 요소들에 빨간 테두리가 그려져요. 함 해보세요. 그나저나 스크립트가 무지 복잡해 보이네요. 제가 보기엔 $kids 로 변수를 사용하는게 제일 핵심처럼 보여요. 바로 jQuery 객체 변수인가 보네요. 사실 jQuery 객체를 어떻게 받아야 하나 그동안 고민해었는데요. ^^ 해결됬네요. 그 외는 뭐 복잡하기만 하지 별 다른건 없어보입니다.

 

예 제  
div 요소의 자식 요소들에 빨간 2줄짜리 밑줄을 그려줍니다.

<!DOCTYPE html>
<html>
<head>
  <style>
  body { font-size:16px; font-weight:bolder; }
  span { color:blue; }
  p { margin:5px 0; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <p>Hello (this is a paragraph)</p>

  <div><span>Hello Again (this span is a child of the a div)</span></div>
  <p>And <span>Again</span> (in another paragraph)</p>

  <div>And One Last <span>Time</span> (most text directly in a div)</div>
<script>$("div").children().css("border-bottom", "3px double red");</script>

</body>
</html>

미리보기

설명 그대롭니다.

 

예 제  
함수에 인자를 세팅하여 선택하고 있습니다.

<!DOCTYPE html>
<html>
<head>
  <style>

  body { font-size:16px; font-weight:bolder; }
  p { margin:5px 0; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <div>
    <span>Hello</span>
    <p class="selected">Hello Again</p>
    <div class="selected">And Again</div>

    <p>And One Last Time</p>
  </div>
<script>$("div").children(".selected").css("color", "blue");</script>

</body>
</html>

미리보기

children 함수에 selected 라는 클래스명을 가진 자식 요소를 선택하도록 인자를 집어 넣었네요. 직관적입니다.

 

자식 요소를 찾는 선택자 기억나시나요? 사실 저도 안납니다. ㅎㅎ;; 함 찾아보시구요. 이번같이 함수가 편하실지 선택자가 편하실지;;; 개인의 취향대로 사용하셔요~. 전 함수가 ㅎㅎㅎ

그럼 즐프하세요.

※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.



출처: http://findfun.tistory.com/181 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/181 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/181 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/181 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/181 [즐거움을 찾자 Find Fun!!]

728x90

function content_print(){
     
                var initBody = document.body.innerHTML;
                window.onbeforeprint = function(){
                    document.body.innerHTML = document.getElementById('선택될 div id').innerHTML;
                }
                window.onafterprint = function(){
                    document.body.innerHTML = initBody;
                }
                window.print();    
            }           
         
 
===============================================================================================
 
<div id="content">
    내용 content_1
</div>
 
<div id="content_2">
   내용 content_2
</div>
<input type="button" value="print" onclick="javascript:content_print();">
================================================================================================
 
선택될 div id  이부분에 div id 를 삽입하면 된다.
print 버튼을 누르면 지정된 div 안의 내용이 프린트 된다.



출처: http://mkwilson.tistory.com/64 [wilson's story]

출처: http://mkwilson.tistory.com/64 [wilson's story]

출처: http://mkwilson.tistory.com/64 [wilson's story]

출처: http://mkwilson.tistory.com/64 [wilson's story]

728x90


I am trying to return a json encoded string from PHP script.

$.post("order.php", { product: product_id, coupon: coupon },
function(data) {
    $("#price").html("$" + data.price);
    $("#discount").html("$" + data.discount);
    $("#total").html("$" + data.total);
});

I tried to use alert function in callback to see returning value from PHP:

{"price":249,"discount":"0.00","total":249}

but value of #price and rest elements is "$undefined".

Please help.

It seems you just have to parse the JSON data into an object using parseJSON() :

$.post("order.php", { product: product_id, coupon: coupon },
function(data) {
    data = $.parseJSON( data );
    $("#price").html("$" + data.price);
    $("#discount").html("$" + data.discount);
    $("#total").html("$" + data.total);
});


+ Recent posts