Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
danielaubuchon
5,728 PointsCan I have some help with my jquery?(code below) What is a more efficient way of doing this.
var $button = ".main-button";
$($button).click(function(){
$($button).text("Nice Site Right?");
$($button).text("Thanks for coming!");
$($button).click(function(){
$($button).text("Check out the about page!");
$($button).click(function(){
$($button).text("Stop clicking the button!");
});
});
3 Answers
Tobiasz Gala
Full Stack JavaScript Techdegree Student 23,529 PointsI think this is what you mean
var $button = ".main-button";
$($button).click(function(){
let counter = 0;
if (counter === '0') {
// do something
counter += 1;
} else if (counter === '1')
//....
});
Tobiasz Gala
Full Stack JavaScript Techdegree Student 23,529 PointsI think this is the easiest solution
const $button = '.main-button';
let counter = 0;
$($button).click(function() {
if (counter === 0) {
$this.text('first text');
counter += 1;
} else if (counter === 1) {
$this.text('second text');
counter += 1;
} else
$this.text('stop clicking!');
});
Jennifer Nordell
Treehouse TeacherHi there! While Tobiasz Gala has given you a great answer, I think I may have an example that might fit your needs a bit better. His will eventually stop changing text, but this solution will allow you to continue to cycle through texts that you put into an array. Take a look:
const $button = ".main-button";
const buttonMessages = ["Nice Site Right?", "Thanks for coming!", "Check out the about page!", "Stop clicking the button!"];
let counter = 0;
changeText();
function changeText() {
$($button).text(buttonMessages[counter % buttonMessages.length]);
counter++;
}
$($button).click(function(){
changeText();
});
Hope this helps and is what you're looking for!
danielaubuchon
5,728 Pointsdanielaubuchon
5,728 PointsIm trying to change the text of a button every time i click it