jQuery addClass example

Change class name on click in jQuery

by tomoshige

HTML

<header>
<a>hoge</a>
<p class="login">
 ほげほげ
</p>
<h1></h1>
</header>
<div style="500px;">

</div>
<div style="height:1400px;" id="movie">
<div id="banner-message">
  <p>Hello World</p>
  <button>Change color</button>
</div>

</div>
<footer style="height: 200px;">
  aaa
</footer>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

header{
  background: transparent;
  position: fixed;
  width: 100%;
}

JavaScript

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
  banner.addClass("alt")
})

    
  $(window).on('scroll', function(){
    //セクション2から3の間はこれ
    if ($(window).scrollTop() > $('#movie').offset().top && $(window).scrollTop() < $('footer').offset().top ) {
      $("header").css("background-color", "#FFFFFF");
      //テキストカラー
      $("header a").css("color", "#000000");
      $("header p.login").css("border", "2px solid #000000");
      //ヘッダー境界線
      $("header").css("border-bottom", "1px solid rgba(0,0,0,0.2)");
      $("header").css("box-shadow", "4px 4px 4px rgba(105,105,105,0.3)");
      //ロゴ
      $("header h1").html("<img src='images/top-logo-ura.png' alt='転職支援ならSCOUTER'>");

    }else {//それ以外(つまりセクション1である場合)はこれ
      $("header").css({
      	'border-bottom': '',
        'box-shadow': '',
      	"background-color":"transparent"});
      $('header a').css('color','');
      $('header p.login').css('border','');
      $('header h1').html('');
    }
    return false;
  });