JQuery alert on TD click - javascript

My project doesn't alert "Test" when I click on any of the "td" Elements.
I will use it for something more useful later but I'm just trying to get it to alert on click, Thank you!
link: http://jsfiddle.net/gk5c9z2z/
$("td").click(function () {
alert("Test");
});

for (var i = 0; i <= Cards.length; 0) { line is the culprit. The last iteration fails as Cards[i] returns undefined and undefined doesn't have setAttribute method. JavaScript interpreter throws an error and subsequent lines are not executed. Change it to:
for (var i = 0; i < Cards.length; 0) {
Also note that you could use i++ instead of 0 as the final-expression of the for loop and remove the i = i + 1; line.

I think you should use
$("td image")
as you are really clicking on the image.

Related

Getting previous element in for loop

EDIT 2 (to make the problem more understandable)
The effect I am trying to achieve is the following: everytime an element enters the viewport an 'is-visible' class is added to it and the same 'is-visible' class is removed from the previous element.
Now I've managed to make it work but I run a for loop to remove all is-visible classes before adding the is-visible class to the element in viewport.
It works but in terms of performance I think it would be better to just remove the class from element[i -1]. And this were I can't get it working.
Here is a simplified fiddle were I try to make the element[i-1] solution work: https://jsfiddle.net/epigeyre/vm36fpuo/11/.
EDIT 1 (to answer some of the questions asked)
I have corrected an issue raised by #Catalin Iancu (thanks a lot for your precious help) by using a modulus operator ((i+len-1)%len).
ORIGINAL QUESTION (not really clear)
I am trying to get the previous element in a for loop (to change its class) with following code :
for (var i = 0; i < array.length; i++) {
if(array[i-1] && my other conditions) {
array[i-1].classList.remove('is-visible');
array[i].classList.add('is-visible');
}
}
But it's not removing the class for [i-1] element.
Here is a more complete piece of code of my module (this is running within a scroll eventlistener):
var services = document.getElementsByClassName('services'),
contRect = servicesContainer.getBoundingClientRect();
for (var i = 0; i < services.length; i++) {
var serviceRect = services[i].getBoundingClientRect();
if ( !services[i].classList.contains('active') && Math.round(serviceRect.left) < contRect.right && services[i-1]) {
services[i-1].classList.remove('is-visible');
services[i].classList.add('is-visible');
}
}
Thanks for your help!
Your if(array[i-1] && my other conditions) is always true, except for the very first case where array[-1] doesn't exist. Therefore, it will remove and then add the active class for each element, which will make it seem as only the first element's class has been removed.
What you need is a better if condition or a break statement, when the loop is not needed anymore
for (var i = 0; i < array.length; i++) {
if(array[i] && i != array.length - 1) {
array[i].classList.remove('active');
}
}
array[array.length - 1].classList.add('active');
The problem probably is that based on your code: services[i-1].classList.remove('active'); and services[i].classList.add('active'); the 'active' class you add in current iteration will be removed in next iteration!
So your code has logical errors, array index does not return all prev items!
What if you create a variable that contain the previous element?
var previous = array[0];
for (var i = 0; i < array.length; i++) {
if(previous && my other conditions) {
previous.classList.remove('active');
array[i].classList.add('active');
break;
}
previous = array[i];
}

Understanding listening for click event from list of nodes using Javascript

So I had built a Boostrap page whereby I have an array (or list) of child nodes for selection from a dropdown menu. I wanted to detect which node had been clicked and then display the value in the new value in the menu button.
Initially I tried to detect a click event via the following code:
for (var i = 0; i < menu.length; i++){
menu[i].firstchild.innerHTML.addEventListener("click", function(){
// Assign value of node clicked on to button
button.childNodes[0].nodeValue = menu[i].firstChild.innerHTML;
});
}
However the above does not work, and menu[i].firstChild.innerHTML always seems to be undefined. I was wondering why this is the case?
I found a solution to the problem using this code from another question:
for (var i = 0; i < menu.length; i++){
(function(index) {
console.log(menu[index]);
menu[index].addEventListener("click", function(){
for (var x = 0; x < menu.length; x++){
if (menu[x] == this){
//alert(x);
//console.log(button.childNodes[0].nodeValue);
button.childNodes[0].nodeValue = menu[x].firstChild.innerHTML;
}
}
}, false);
})(i);
}
From: Detecting which node was clicked in javascript
However, I fail to really understand what is going on here. What are we actually passing into the first for loop? This seems to be (function(index){//code})(i); I can't say I have seen this syntax before. Then what is the purpose of the second for loop?
I would be very grateful if a better programmer than myself could explain to me what is going on here.
Kind Regards,
In your initial code you addEventListener to innerHTML which is string and is deaf to click. Easy fix is possible.
for (var i = 0; i < menu.length; i++){
menu[i].firstchild.addEventListener("click", function(){
// Assign value of node clicked on to button
//**this** is "clicked" element and what was previously menu[i].firstChild
//menu[i] is out of scope here (i == menu.length or something else)
//button is hopefully in global scope.
button.childNodes[0].nodeValue = this.innerHTML;
});
}

Run a for loop. Increment the value; exit and begin loop again with new value

I want to run a loop. I want it to excecute it 16 times like,
for (var i = 0; i <= 15; i++) {
alert(i);
}
I want this loop to run on clicking a button. But the loop should only return the first value of i and then exit. Like this,
for (var i = 0; i <= 15; i++) {
alert(i);
exit();
}
What I am confused with is, whenever I click the button I want this loop to run-only once-but with the value being incremented by one. The whole idea is to alert the i value on each click of the button but incremented by one each time. I think even my use of for loop also is not making any sense. Or is my whole logic wrong. I think I am doing something more complex where something simple like using counter will accomplish the same. Any help appreciated.
var myVal = 0;
function incrementValue(){
myVal++;
alert(myVal);
}
Just increment a variable every time you call the function.
If I am getting it right, it should be somewhat like this,
var btn_init = 0;
//on click
$(function(){
$('#your_button_id').on('click',function(){
btn_init++; //increment
alert(btn_init);
}
});
<div class="button1">click</div>
<div class="valuecontainer"></div>
<script>
var i=0;
var x=15;
$('.button1').click(function(){
if(i<x){
i++;
$('.valuecontainer').html(i);
}
else
{
alert("rechaed limit");
}
});
</script>
I guess you will find your answer here:
Count function call in JS
This is the shortest code found there though i donot completely understand this (somebody plz explain):
function myFunction() {
this.num = (this.num || 0) + 1;
if(this.num <= 15)
alert(this.num);
}

How do I correctly use an iteration value in JavaScript?

I am creating a 'simple' javaScript function which basically displays new information on the page when a user clicks next or previous.
The information is taken from an array and I want to use either i++ or i-- to call an element of the array.
Heres my JavaScript:
var titles = ["Dundalk", "Navan", "Drogheda", "Dublin"];
var i = 0;
function next()
{
i++;
if (i == titles.length)
{
i = 0;
}
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
function prev()
{
if (i == 0)
{
i = titles.length;
}
i--;
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
The problem is, when I run this code in my HTML page, I get an 'UNDEFINED' result. The JavaScript is not recognizing that i has been initialized as 0 in the beginning.
If i change titles[i] to titles[2], for example, the correct text is displayed in HTML.
What am I forgetting or how can I overcome this?
Thanks
The fact that you're seeing undefined indicates that you're accessing an array index which hasn't been set. Your code looks fine at a glance, so I would guess that there's some more code you're not showing which also uses i as a loop variable and leaves it set to a value > titles.length after the code above has run.

Iterate focus components in javascript

I have some links and want to pass the focus one by one automatically.
I'm using the code below. Works fine passing the focus but only once.
The first time the focus pass, the link change the color, then pass to the next. The one before gets black again and the next is painted red. No problem.
But when its reach the final link doesn't restart.
var i = 0;
var letras = document.getElementsByTagName("a");
function pasaLink() {
if (i == 0) {
letras[letras.length-1].style.color = "black";
} else {
letras[i-1].style.color = "black";
}
letras[i].style.color = "red";
letras[i].focus();
i++;
if (i > letras.length) {
i= 0;
}
setTimeout("pasaLink()",2000);
}
With the final if and i=0; I'm trying to get back to the initial index when reach the final element, and then restart to iterate the entire collection of links in letras.
This function is called in the body.onload().
Any ideas why its not working?
Change your if to:
if (i >= letras.length) {
i= 0;
}
Working example:
http://jsfiddle.net/nivas/Nn62Q/
(click the Orig Button to see the behavior of your code and the New button to see the behavior of the new one. I have added a try...catch to show the error)
Explanation:
Let us say there are five a tags.
You make i = 0 when i > 6 (i.e., 6). But when i becomes 5, letras[i].style.color = "red"; at the beginning of the function fails and an exception is throws a exception. The flow stops here so the if (i > letras.length) will never be reached.
Shouldn't your condition be
if (i == letras.length) {
i= 0;
}
instead?
Once i is equal to the length of your array, reset.

Categories