toggle class on click Javascript - javascript

I want to know WHY its not working.
I have a bunch of classes called yellow.
I then add an event listener to them with a callback function to activate upon clicking. What am I not seeing here? :(
function test(){
var allYellow = document.querySelector('.yellow');
allYellow.addEventListener('click', function(){
this.classList.toggle = 'testyellow';
})
}
test();

In JavaScript..
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("mystyle");
}

Related

Stuck in JavaScript Adding Class

for(i=0;i<document.querySelectorAll(".skill-images").length;i++){
document.querySelectorAll(".skill-images")[i].addEventListener("click", function (){
document.querySelectorAll(".skill-images")[i].classList.add("imghover");
setTimeout(function(){
document.querySelectorAll(".skill-images")[i].classList.remove("imghover");
},500);
});
}
Where am i going wrong? I just need to add a class imghover on a click.
My all images have a class = "skill-images:
Please someone check and solve it!
You're binding a click event, which is triggered when user clicks on the element, not hover over it. If possible, it's better to stick to css for hover states and do it like this:
.skill-images:hover {
// Put here your rules which were defined for .imghover
}
try this
var skillImagesElement = document.querySelectorAll(".skill-images");
for(var i=0; i<skillImagesElement.length;i++){
skillImagesElement[i].addEventListener("click", function (e) {
var eachElement = this;
eachElement.classList.add("imghover");
setTimeout(function(){
eachElement.classList.remove("imghover");
},500);
},false);
}

Dynamically created buttons won't fire when clicked

I'm creating buttons based on what a user enters into an input box. However, the function i have linked to the dynamically created buttons won't fire when pressed.
function btnCreate() {
num++;
userBtn = $("<button>")
userBtn
.addClass("btn search-term-btn dynamicElement")
.appendTo($(".btn-holder"))
.text(topics)
.attr("data-name", topics);
usedTopics.push(topics + num);
topics = [];
console.log(num);
};
$(".search-term-btn").on("click", ".dynamicElement", function () {
// takes the name of the button
searchValue = $(".search-term").attr("data-name");
console.log(searchValue);
})
The class is correct, ive checked with the inspector. I just can't seem to figure out why it's unresponsive
Create the click event on DOM.
$(document).on("click", ".search-term-btn .dynamicElement", function () {
console.log(this)
});
while you are creating the buttons, you can add the onclick function there..
like userBtn = $("<button onlcikc="somefunction(this)">")
OR
you can use on function which is
$('body').on( "click",".dynamicElement", function() {
//your code
});

Why doesn't the form entry update after button click [JS]?

I am writing a little script which should do the following actions:
1) a button click triggers a form to load.
2) an entry of the form is filled with a specific value.
My code looks something like this:
document.getElementById('formButton').click();
window.onload = function(){
document.getElementById('formEntry').value = "foo";
};
This script loads the form,but the form entry doesn't update.
I suppose that the problem is that the form entry hasn't loaded in the DOM yet, but onload doesn't seem to do the job... Any hints on what I'm doing wrong here?
Do this -
1) You have to put all of the document variables inside window.onload
window.onload = function() {
var formEntry = document.getElementById('formEntry');
var formButton = document.getElementById('formButton');
};
2) You have to change the formEntry when the formButton is clicked, so put the .value change inside another function like so
window.onload = function() {
var formEntry = document.getElementById('formEntry');
var formButton = document.getElementById('formButton');
formButton.addEventListener('click', function() {
formEntry.value = "foo";
});
};
or alternatively
window.onload = function() {
document.getElementById('formButton').addEventListener('click', function() {
document.getElementById('formEntry').value = "foo";
});
};
You should bind the button click to an event listener:
window.onload = function(){
document.getElementById('formButton').addEventListener('click',function(){
document.getElementById('formEntry').value = "foo";
});
};
By calling the .click() function you just trigger any given click event listeners, but you haven't declared one, and thats also propably not your intention.

Why is the button disapearing?

The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>
There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>
What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced
remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().

How can I add an onclick handler on a dynamic element?

Here is the important part of my JS code:
function createClose() {
var cButton = document.createElement("img");
cButton.src = "close.gif";
cButton.style.cursor = "pointer";
cButton.onclick = closeWindow;
document.getElementById("my_window").appendChild(cButton);
}
function closeWindow() {
document.getElementById("my_window").style.display = "none";
}
The image gets created and appended, but there is no onClick event invoked when it is clicked. I also tried using an anonymous function, but that didn't work either.
No, I'm not going to use jQuery (although I believe you that it's easier).
input.setAttribute('onclick','handleClick();');
input = document.getElementById("my_window").appendChild(cButton);
input.onclick = function() { yourFunction(); };
This question is almost a duplicate of "Add onclick property to input with JavaScript"
As an alternative way I've seen the use of input.setAttribute('onclick', 'yourFunction();'); too but cannot guarantee it works.

Categories

Resources