v2.5.2
Giriş yap

jQuery kodu Vanilla Javascript'e çevirme

s74k3
284 defa görüntülendi

Merhaba. Sitemdeki jquery bağımlılığını kaldırmak istiyorum.
Aşağıdaki jquery kodunu vanilla javascript'e çevirmem lazım. Yardımcı olursanız sevinirim.

Codepen Linki

jQuery

$(function () {
	$(".replybutton").on("click", function () {
		$(".replybox").hide();
		var commentboxId = $(this).attr("data-commentbox");
		$("#" + commentboxId).toggle();
	});

	$(".cancelbutton").on("click", function () {
		$(".replybox").hide();
	});
});

HTML

<div class="item">
	<p>Comment 1: This is comment 1</p>
	<button class="replybutton" data-commentbox="panel1">Reply</button>
	<div class="replybox" id="panel1" style="display:none">
		<textarea cols="35" rows="3"></textarea>
		<br>
		<button class="cancelbutton">Cancel</button>
	</div>
</div>
<div class="item">
	<p>Comment 2: This is comment 2</p>
	<button class="replybutton" data-commentbox="panel2">Reply</button>
	<div class="replybox" id="panel2" style="display:none">
		<textarea cols="35" rows="3"></textarea>
		<br>
		<button class="cancelbutton">Cancel</button>
	</div>
</div>

Bu şekilde yapmaya çalıştım fakat çalışmadı.

document.addEventListener("DOMContentLoaded", () => {
	document.getElementByClassName("replybutton").on("click", function () {
		document.getElementByClassName("replybox").style.display = "none";
		let commentboxId = this.attr("data-commentbox");
		$("#" + commentboxId).toggle();
	});
	document.getElementByClassName("cancelbutton").on("click", function () {
		document.getElementByClassName("replybox").style.display = "none";
	});
});
megasteve
640 gün önce

Vanilla JavaScript'te hepsine direkt event atayayım gibi bir seçeneğimiz yok. Bu yüzden foreach zorunlu. Ayrıca getElementByClassName değil getElemenstByClassName olmalıydı. Arada çok küçük bir 's' takısı var.

Umarım iç içe geçen callbackler seni korkutmaz, sorunun cevabı;

document.addEventListener('readystatechange', function()
{
    if(document.readyState === 'complete')
    {
        document.querySelectorAll('.replybutton').forEach(function(replyButton)
        {
            replyButton.addEventListener('click', function()
            {
                document.querySelectorAll('.replybox').forEach(replyBox => replyBox.style.display = 'none');
                var commentBoxId = this.getAttribute('data-commentbox');
                document.getElementById(commentBoxId).style.display = 'block';
            });
        });

        document.querySelectorAll('.cancelbutton').forEach(function(cancelButton)
        {
            cancelButton.addEventListener('click', function()
            {
                document.querySelectorAll('.replybox').forEach(replyBox => replyBox.style.display = 'none');
            });
        });
    }
});