Click a button with tasks involved such as highlight and scroll - javascript

How do you make a button do a certain task instead of just a click? I am trying to put a highlight on text and scroll on a button when you click on it. The for loop and if statement inside the function is correct? Also, I saw in a post to put extra parenthesis around beginning and end of the function. Is that correct? Please help fix this code. Thank you!
var press = document.createElement('press');
press.onclick = (function () {
for (var q = 0; q < i; q++) {
if ( x == y ) {
document.getElementById(x).scrollIntoView(true);
$('body').text().highlight(x);
}
}
})();

I have difficulty understanding your question but I will attempt answering it based on your code.
'How do you make a button do a certain task instead of just a click?'
You add an event listener to the button, disable the default behavior and write the task in the listeners callback.
btnElement.addEventListener('click', (e)=>{
e.preventDefault();
//Code for your task
});
The for loop and if statement inside the for loop is correct?
I am not sure if its a question or statement. Syntactically it looks correct, but I cannot say more without proper context. What is x? Please provide a working sample or more code.
Also, I saw in a post to put extra parenthesis around beginning and end of the function. Is that correct?
You do that only when you want to have an IFFE (https://en.wikipedia.org/wiki/Immediately-invoked_function_expression). Basically, you call the anonymous function right after defining it.
Please help fix this code. Thank you!
Please go over the points mentioned above and make changes to your code. In order to help you fix the code I need more information about what you are trying to do. The best I can do is add indentation.
var press = document.createElement('button'); //Create a button element.
press.onclick = (function () {
for ( var q = 0; q < x.length; q++) {
if ( x == y ) {
document.getElementById(x).scrollIntoView(true);
$('body').text().highlight(x);
}
}
})();

Related

How to have a variable increase over time (JS)

i was wondering how to make a variable go up over time, ive tried to do this -->
var i = 1;
var c = document.getElementById("click");
function workers() {
if (click >= workers*50000)) {
click += -(workers*50000)
click += i++
c.innerHTML = click;
}
}
but it hasnt worked, how do i fix this?
you could do this
let i = 0;
// instead of 2000 insert the frequency of the wanted update (in milliseconds)
const incrementInterval = setInterval(() => i++, 2000)
// when you want it to stop it
clearInterval(incrementInterval)
anyway, i don't really understand how the code supplied with the question has anything to do with it
You have an element and a variable 'click', which tells me you're really not wanting to grow over time per se, but rather grow with every click.
Another difficulty is finding out what you're trying to do with multiplying by 50000. I am assuming you are trying to reset the count after 50000.
One big thing you're missing is the actual association of the click event to your 'click' HTML element. Below, I'm using addEventListener to do that. From there, I'm resetting the counter to '1' if 'i' goes above '5' (I use 5 just to show the reset in a reasonable number of clicks). Then I take the value of 'i' and put it into the innerHTML label of the element that triggered the event.
var i = 1;
document
.getElementById("click")
.addEventListener('click', function(e) {
if (i > 5)
i = 1;
e.target.innerHTML = `click: ${i++}`;
})
<div id='click'>click<div>
Define your question better. What is your goal? What has your code achieved? What result are you getting and how is it different than your expectations? What is 'i' meant to be used for? How does it interact with the function? Why are you multiplying it with 50000? Is workers a separate variable that's globally defined and not shown? Communication is an important skill in this field, and comments are often helpful tools to document your code for others to understand.
I think an alternative answer could be formatted in this way:
let i = 0;
function increment(){
i++;
document.querySelector('h3').textContent = i
}
document.querySelector('button').addEventListener('click',increment)
<button>Click Me</button>
<h3>0</h3>

Asking if variable is equal to an integer inside jquery click not working

The title really explains most of it, but basically, this should alert when I get the click the element, but it doesn't. It also does work when I put the alert() outside of the if, and in the beginning of the jquery on click. Here's my code:
var hasClickedWelcome = 0;
//Onclick event
$(".menu-welcome" ).click(function() {
var welcomeButton = document.getElementByClassName("menu-welcome");
if(hasClickedWelcome == 0) {
alert("hello");
$(".menu-welcome").addClass("menu-welcome-clicked");
hasClickedWelcome = 1;
} else {
welcomeButton.classList.remove("menu-welcome-clicked");
hasClickedWelcome = 0;
}
});
Your if statement has no meaning
if(hasClickedWelcome == hasClickedWelcome)
This will always return true, you'll always hit this code no matter what:
alert("hello");
$(".menu-welcome").addClass("menu-welcome-clicked");
hasClickedWelcome = 1;
Therefore, you have a clear logic problem.
Edit: See Daniel Beck suggestion on comments section
Initially, you have syntactic error, there is no inbuild function like document.getElementByClassName() (unless its your custom function), so clearly even if you put your alert in beginning of click it won't work.
Also, you are checking if(hasClickedWelcome == hasClickedWelcome) which does not make sense.
Use: document.getElementsByClassName("menu-welcome"); to get array of nodes having the class. Then, rest of your logic accordingly.
//Onclick event
$(".menu-welcome" ).click(function() {
// in jQuery "this" refers to the element that was selected in a callback
// it looks like toggleClass is really what you're looking for
$(this).toggleClass("menu-welcome-clicked");
});

javascript: var i is not defined? (clearly defined)

WHAT I WANT TO HAPPEN
So what I want to happen is function partA() to click button [z] every 2 seconds. The button that is being clicked should change, because the script is a looping script, so for instance. The first loop, it would click button 1, then button 2, then button 3, because var z = 1 + i++. Is this possible? z is supposed to equal the number 1, plus the loop number. This should loop as long as variable i is less than 50.
WHAT IS HAPPENING
It works properly, looping and all, if I test the script without variable z. However, without variable z, I have to manually change the number that would equal z, which is painstaking, and annoying.
var z = 1 + i++
for(i=0;i<50;i++) {
setInterval(partA, 2000);
function partA() {
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[z].click();
}
}
Should i++ be defined another way? The error I'm getting when running the script in console is:
Uncaught ReferenceError: i is not defined (...)
at :2:13
at Object.InjectedScript._evaluateOn (:878:140)
at Object.InjectedScript._evaluateAndWrap (:811:34)
at Object.InjectedScript.evaluate (:667:21)
There's a couple of suggestions I could advise with your code so I'll try and address each one individually.
Firstly define your function outside of your loop. If you would like to know the reasons behind this please read: Don't make functions within a loop
Secondly you should really declare i as a variable to set the scope to which it applies. Some good information on this is at: Declaring variables without var keyword
Thirdly when you run your loop you could run the code inside an IIFE. The reason for this is when you run setInterval, by the time it runs i will actually be 3 (or the last number of your loop). This is due to the asynchronous nature of setInterval, and that the reference to i is bound to the function, not the value of i.
Example
for(var i=0;i<3;i++) {
(function(i) {
setInterval(clickButton(i), 2000);
})(i)
}
function clickButton(idx) {
return function() {
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[idx].click();
}
}
JSBin Demo
http://jsbin.com/harigewuze/edit?html,js,output
Why are you trying to define z outside the loop? Just use i.
for (var i = 0; i < 50; i++) {
...
document.getElementsByTagName('button')[i].click();
}
without changing your code too much I would write it like this...
you know its looping 50 times, you know i is incrementing from 0 to 49, use i to change the button name and you don't need z...
for(i=0;i<50;i++) {
setInterval(partA, 2000);
function partA() {
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[i + 1].click();
}
}
1) This is how you want your code to look like :
var z;
for(i=0;i<50;i++) {
z=i;
setInterval(partA, 2000);
}
function partA() {
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[z].click();
}
2) Unfortunately, in javascript you have a problem with this code due to the fact of scopes. My recommendation is to read this link first http://www.mennovanslooten.nl/blog/post/62 and understand how it works.
If you did understand it, then thumb up..you just promoted yourself to a higher level in javascript ;)
3) If you are still having issues, post it on JSFiddle

Trying to make sense of "this" in my javascript code (one thing works, the other doesn't)

I've been trying to learn javascript by refactoring some Jquery examples in a book into javascript. In the following code I add a click listener to a tab and make it change to active when the user clicks on the tab.
var tabs = document.querySelectorAll(".tabs a span");
var content = document.querySelectorAll("main .content li");
for (var tabNumber = 0; tabNumber <= 2; tabNumber++) {
tabs[tabNumber].addEventListener("click", function (event) {
for (var i = 0; i < tabs.length; i++) {
tabs[i].classList.remove("active");
}
tabs[tabNumber].classList.add("active");
for (var i = 0; i < content.length; i++) {
content[i].innerHTML = "";
}
event.preventDefault();
});
}
This returns an undefined error when I run it. However, I tried replacing tabs[tabNumber].classList.add("active") with this.classList.add("active") and it worked.
Why doesn't the previous code work? As far as I can see they are referring to the same thing, and tabs[tabNumber] should work since at that point in the code it is tabs[0].
If use this, I think it's better and a more polished solution. If you still want to use tabNumber, it's probably evaluating to 3 in every click callback, because it's the number after the last iteration, and you don't have a tabs[3] position.
So, you just have to make a closure of the tabNumber variable.
I guess other answers told you why tabs[tabNumber] does not work (because it comes from the score of the for loop and so, is always equal to the greater value of tabNumber).
That's why I would recommend using a .forEach loop. Careful though because it doesn't work on arrays of DOM nodes produced by document.querySelectorAll(), but you can use:
// ES6
Array.from(document.querySelectorAll('...'))
// ES5
[].slice.call(document.querySelectorAll('...'))
Anyway, I made a simplified working demo of your code.
Note that I save the currently active tab in a variable, to prevent another for loop. You could also do:
document.querySelector('.active').classList.remove('active')
But I like to reduce the amount of DOM reading.
Good luck for your apprentissage, re-writing some jQuery code into Vanilla JS seems like a good method, and you might acquire a far better comprehension of JavaScript.

Command Buttons Not Responding to JS functions

I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)

Categories

Resources