Tüm blog yazıları

JavaScript DOM: Web Sayfası Üzerindeki Stilleri Değiştirme

Web sayfaları sadece HTML ile iskelet haline gelir. Görsel görünüm ve düzen CSS ile sağlanırken, bu sayfanın dinamik olarak değiştirilmesi JavaScript’in alanıdır. JavaScript sayesinde bir elementin rengi değiştirilebilir, yazı tipi büyütülebilir ya da kenarlık eklenebilir. Bu makalede, bir HTM

eminbasbayan4 dk okuma
JavaScript DOM: Web Sayfası Üzerindeki Stilleri Değiştirme

CSS ile sayfalarımızı güzelleştiriyoruz. Peki ya kullanıcı bir butona tıkladığında rengi değiştirmek istersek? Ya da bir elementi dinamik olarak gizlemek/göstermek istersek?

JavaScript ile elementlerin CSS stillerini okuyabilir ve değiştirebilirsiniz. Bu makalede style property'si ve getComputedStyle metodunu öğreneceğiz.

style Property'si

Her elementin bir style property'si vardır. Bu property üzerinden inline stil ekleyebilirsiniz.

Temel Kullanım

javascript
const element = document.querySelector("#kutu");

// Stil değiştirme
element.style.color = "red";
element.style.backgroundColor = "yellow";
element.style.fontSize = "20px";

HTML'deki Karşılığı

JavaScript ile eklenen stiller inline style olarak eklenir:

javascript
element.style.color = "red";
element.style.padding = "10px";

Bu kod şuna eşdeğerdir:

html
<div style="color: red; padding: 10px;">...</div>

CSS Property İsimlendirmesi

CSS'te tire (-) ile yazılan property'ler JavaScript'te camelCase yazılır:

CSSJavaScript
background-colorbackgroundColor
font-sizefontSize
border-radiusborderRadius
margin-topmarginTop
text-decorationtextDecoration
z-indexzIndex
box-shadowboxShadow

Örnekler

javascript
const kutu = document.querySelector(".kutu");

// CSS: background-color → JS: backgroundColor
kutu.style.backgroundColor = "lightblue";

// CSS: font-size → JS: fontSize
kutu.style.fontSize = "18px";

// CSS: border-radius → JS: borderRadius
kutu.style.borderRadius = "10px";

// CSS: margin-top → JS: marginTop
kutu.style.marginTop = "20px";

// CSS: text-align → JS: textAlign
kutu.style.textAlign = "center";

Tire Kullanırsanız Hata Alırsınız!

javascript
// ❌ YANLIŞ - Hata verir
kutu.style.background-color = "red";  // SyntaxError

// ✅ DOĞRU
kutu.style.backgroundColor = "red";

Değer Formatı

Stil değerleri string olarak verilmelidir ve gerekli birimler dahil edilmelidir:

javascript
// ✅ Doğru - birim dahil
element.style.width = "200px";
element.style.fontSize = "1.5rem";
element.style.marginTop = "2em";
element.style.opacity = "0.5";  // Birimsiz değerler de string

// ❌ Yanlış - birim yok
element.style.width = 200;      // Çalışmaz!
element.style.fontSize = 1.5;   // Çalışmaz!

Stil Okuma

style property'si sadece inline stilleri okuyabilir. CSS dosyasındaki stilleri okuyamaz!

Örnek

html
<style>
    #baslik {
        color: blue;
        font-size: 24px;
    }
</style>

<h1 id="baslik">Merhaba</h1>
javascript
const baslik = document.querySelector("#baslik");

// CSS dosyasından gelen stili okumaya çalış
console.log(baslik.style.color);     // "" (boş string!)
console.log(baslik.style.fontSize);  // "" (boş string!)

// Inline stil ekle
baslik.style.color = "red";

// Artık okuyabilirsin (inline olduğu için)
console.log(baslik.style.color);     // "red"

Neden Boş Döner?

element.style sadece HTML'deki style attribute'unu okur. CSS dosyasındaki veya <style> etiketindeki stilleri görmez.

getComputedStyle()

Bir elementin gerçek/hesaplanmış stilini okumak için getComputedStyle() kullanılır:

Sözdizimi

javascript
window.getComputedStyle(element)

Örnek

html
<style>
    #kutu {
        width: 200px;
        height: 100px;
        background-color: coral;
        font-size: 16px;
    }
</style>

<div id="kutu">İçerik</div>
javascript
const kutu = document.querySelector("#kutu");

// style ile okuma (CSS'ten gelen stiller görünmez)
console.log(kutu.style.width);           // "" (boş)
console.log(kutu.style.backgroundColor); // "" (boş)

// getComputedStyle ile okuma (her şeyi görür)
const stiller = window.getComputedStyle(kutu);
console.log(stiller.width);           // "200px"
console.log(stiller.backgroundColor); // "rgb(255, 127, 80)"
console.log(stiller.fontSize);        // "16px"

Önemli Notlar

  1. getComputedStyle() sadece okuma içindir, stil değiştiremezsiniz
  2. Renkler RGB formatında döner
  3. Tüm değerler string olarak döner
javascript
const stiller = window.getComputedStyle(element);

// ❌ Değiştirmeye çalışmak işe yaramaz
stiller.color = "red";  // Hiçbir etkisi yok!

// ✅ Değiştirmek için style kullan
element.style.color = "red";

Pratik Örnekler

Örnek 1: Hover Efekti (JavaScript ile)

html
<div id="kart">Üzerime gel!</div>
javascript
const kart = document.querySelector("#kart");

// Başlangıç stilleri
kart.style.padding = "20px";
kart.style.backgroundColor = "#f0f0f0";
kart.style.transition = "all 0.3s ease";
kart.style.cursor = "pointer";

// Mouse üzerine gelince
kart.addEventListener("mouseenter", function() {
    this.style.backgroundColor = "#007bff";
    this.style.color = "white";
    this.style.transform = "scale(1.05)";
});

// Mouse ayrılınca
kart.addEventListener("mouseleave", function() {
    this.style.backgroundColor = "#f0f0f0";
    this.style.color = "black";
    this.style.transform = "scale(1)";
});

Örnek 2: Karanlık/Aydınlık Mod

html
<button id="tema-btn">Karanlık Mod</button>
javascript
const temaBtn = document.querySelector("#tema-btn");
let karanlikMod = false;

temaBtn.addEventListener("click", function() {
    if (karanlikMod) {
        // Aydınlık moda geç
        document.body.style.backgroundColor = "white";
        document.body.style.color = "black";
        this.innerText = "Karanlık Mod";
    } else {
        // Karanlık moda geç
        document.body.style.backgroundColor = "#1a1a1a";
        document.body.style.color = "white";
        this.innerText = "Aydınlık Mod";
    }
    karanlikMod = !karanlikMod;
});

Örnek 3: Element Gizle/Göster

html
<button id="toggle-btn">Gizle</button>
<div id="icerik">Bu içerik gizlenebilir.</div>
javascript
const toggleBtn = document.querySelector("#toggle-btn");
const icerik = document.querySelector("#icerik");
let gorunur = true;

toggleBtn.addEventListener("click", function() {
    if (gorunur) {
        icerik.style.display = "none";
        this.innerText = "Göster";
    } else {
        icerik.style.display = "block";
        this.innerText = "Gizle";
    }
    gorunur = !gorunur;
});

Örnek 4: Opacity ile Gizleme (Animasyonlu)

javascript
const element = document.querySelector("#element");

// CSS'te transition ekle
element.style.transition = "opacity 0.5s ease";

// Gizle (yavaşça kaybolur)
element.style.opacity = "0";

// Göster (yavaşça belirir)
element.style.opacity = "1";

Örnek 5: Tüm Linklerin Stilini Değiştirme

javascript
const linkler = document.querySelectorAll("a");

linkler.forEach(link => {
    link.style.color = "#e91e63";
    link.style.textDecoration = "none";
    link.style.fontWeight = "bold";
    link.style.transition = "color 0.2s";
});

Örnek 6: Rastgele Arka Plan Rengi

html
<button id="renk-btn">Renk Değiştir</button>
javascript
const renkBtn = document.querySelector("#renk-btn");

function rastgeleRenk() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r}, ${g}, ${b})`;
}

renkBtn.addEventListener("click", function() {
    document.body.style.backgroundColor = rastgeleRenk();
});

Örnek 7: Boyut Artırma/Azaltma

html
<div id="kutu">Kutu</div>
<button id="buyut">Büyüt</button>
<button id="kucult">Küçült</button>
javascript
const kutu = document.querySelector("#kutu");
const buyutBtn = document.querySelector("#buyut");
const kucultBtn = document.querySelector("#kucult");

// Başlangıç boyutu
let boyut = 100;
kutu.style.width = boyut + "px";
kutu.style.height = boyut + "px";
kutu.style.backgroundColor = "coral";
kutu.style.transition = "all 0.3s ease";

buyutBtn.addEventListener("click", function() {
    boyut += 20;
    kutu.style.width = boyut + "px";
    kutu.style.height = boyut + "px";
});

kucultBtn.addEventListener("click", function() {
    if (boyut > 20) {
        boyut -= 20;
        kutu.style.width = boyut + "px";
        kutu.style.height = boyut + "px";
    }
});

Örnek 8: Mevcut Stili Okuyup Değiştirme

javascript
const baslik = document.querySelector("h1");

// Mevcut font boyutunu al
const stiller = window.getComputedStyle(baslik);
const mevcutBoyut = parseInt(stiller.fontSize);  // "32px" → 32

// %50 büyüt
const yeniBoyut = mevcutBoyut * 1.5;
baslik.style.fontSize = yeniBoyut + "px";

Örnek 9: Progress Bar

html
<div id="progress-container" style="width: 300px; background: #eee; border-radius: 5px;">
    <div id="progress-bar" style="width: 0%; height: 20px; background: #4caf50; border-radius: 5px;"></div>
</div>
<button id="basla-btn">Başla</button>
javascript
const progressBar = document.querySelector("#progress-bar");
const baslaBtn = document.querySelector("#basla-btn");

baslaBtn.addEventListener("click", function() {
    let yuzde = 0;
    progressBar.style.transition = "width 0.1s linear";

    const interval = setInterval(function() {
        if (yuzde >= 100) {
            clearInterval(interval);
        } else {
            yuzde++;
            progressBar.style.width = yuzde + "%";
        }
    }, 50);
});

Birden Fazla Stil Ekleme

Yöntem 1: Tek Tek Atama

javascript
element.style.color = "white";
element.style.backgroundColor = "black";
element.style.padding = "10px";
element.style.borderRadius = "5px";

Yöntem 2: cssText Kullanma

Tüm stilleri tek seferde atamak için:

javascript
element.style.cssText = "color: white; background-color: black; padding: 10px; border-radius: 5px;";

Dikkat: cssText mevcut inline stillerin üzerine yazar!

Yöntem 3: Object.assign (Alternatif)

javascript
Object.assign(element.style, {
    color: "white",
    backgroundColor: "black",
    padding: "10px",
    borderRadius: "5px"
});

Stili Sıfırlama

Bir stili kaldırmak için boş string atayın:

javascript
// Stili kaldır
element.style.color = "";
element.style.backgroundColor = "";

// Veya tüm inline stilleri kaldır
element.style.cssText = "";

// Veya removeProperty kullan
element.style.removeProperty("color");
element.style.removeProperty("background-color");  // CSS formatında

style vs CSS Sınıfları

Birçok stil değişikliği için CSS sınıfları kullanmak daha iyidir:

css
/* CSS dosyasında */
.vurgulu {
    background-color: yellow;
    font-weight: bold;
    padding: 5px;
}
javascript
// ❌ Çok fazla inline stil
element.style.backgroundColor = "yellow";
element.style.fontWeight = "bold";
element.style.padding = "5px";

// ✅ Daha temiz - class ekle
element.classList.add("vurgulu");

Bir sonraki makalede classList konusunu detaylı öğreneceğiz!

Özet

javascript
const element = document.querySelector("#element");

// STİL DEĞİŞTİRME
element.style.color = "red";
element.style.backgroundColor = "yellow";
element.style.fontSize = "20px";
element.style.marginTop = "10px";

// BİRDEN FAZLA STİL
element.style.cssText = "color: red; padding: 10px;";

// STİL OKUMA (sadece inline)
console.log(element.style.color);

// HESAPLANMIŞ STİL OKUMA (tümü)
const stiller = window.getComputedStyle(element);
console.log(stiller.fontSize);

// STİLİ KALDIRMA
element.style.color = "";
element.style.removeProperty("background-color");
YöntemKullanımNot
element.style.xTek stil değiştirmecamelCase kullan
element.style.cssTextÇoklu stil atamaÜzerine yazar
getComputedStyle()Stil okumaSadece okuma

Sırada Ne Var?

style property'si ile inline stil ekledik. Ancak gerçek projelerde genellikle CSS sınıfları kullanılır.

Bir sonraki makalede classList konusunu öğreneceğiz - CSS sınıflarını ekleme, kaldırma ve değiştirme yolları.

JavaScript Classes ile pratik uygulamalar, metotlar arası iletişim ve gerçek dünya kod örnekleri
JavaScript Dersleri9 dk okuma

JavaScript Classes - Pratik Uygulamalar

JavaScript class'ları ile pratik uygulamalara geçin! Metotlar arası iletişimden constructor'da metot çağırmaya, kod tekrarını azaltmaktan gerçek dünya senaryolarına kadar class kullanımının inceliklerini keşfedin. Kendi alışveriş sepeti örneğinizle bilginizi pekiştirin.

Yazıyı oku
JavaScript class yapısını gösteren bir kod örneği, ES6 ile modern nesne oluşturma
JavaScript Dersleri9 dk okuma

JavaScript Classes

ES6 ile JavaScript'e gelen class yapısı sayesinde nesne oluşturmak artık çok daha kolay ve düzenli! Constructor function karmaşasından kurtulup, okunabilir ve yönetilebilir kodlar yazmak isteyenler için modern JavaScript'in temel taşı olan class'ları tüm detaylarıyla keşfedin. Bu rehberle nesne şabl

Yazıyı oku
JavaScript kodunda Constructor Function ve new keyword'ü ile nesne oluşturma örnekleri
JavaScript Dersleri8 dk okuma

Constructor Functions ve new Keyword

Factory Function'ların hafıza israfı sorununa Constructor Function'lar ve new keyword'ü ile son verin! Metotları paylaştırarak JavaScript objelerini daha verimli nasıl oluşturacağınızı, new'in perde arkasında neler yaptığını ve prototype sisteminin gücünü bu rehberde keşfedin.

Yazıyı oku

Çerez tercihlerin

Platformun çalışması için zorunlu çerezler kullanıyoruz. İzin verirsen anonim kullanım verilerini ölçüyoruz. Ayrıntıları incele