Reputation:
Take a look at this script:
$(document).ready(function(){
$("#btn").click(function(){
if ($(this).text() == "Hello!"){
$(this).text("Hey!");
$("#div").slideToggle();
return false;
};
if ($(this).text() == "Hi!"){
$(this).text("Hallo!");
$("#div").slideToggle();
return false;
};
});
});
When press the #btn when it have the text "Hello!" the text in #btn changes to "Hey!" and the when press the #btn when it have the text "Hi!" the text changes to "Hallo!". Besides the text change the rest of the actions is identical.
Is there maybe any better way to write this with less code? Maybe something like this (the code dont work but you see the idea):
$(document).ready(function(){
$("#btn").click(function(){
if ($(this).text() == "Hello!", "Hi!"){
$(this).text("Hey!", "Hallo!");
$("#div").slideToggle();
return false;
};
});
});
Upvotes: 1
Views: 52
Reputation: 206078
var arr = ["Hello!", "Hi!", "Hey!", "Aloha!", "Bok!", "Tchuss!"];
$("#btn").text( arr[0] ).click(function(){ // Set initial greet + Click handler.
arr.push( arr.shift() ); // Push first key to last place...
$(this).text( arr[0] ); // and get always the resulting first one
});
I'm not sure what you're trying to do with the slideToggle()
so I missed that part. You're free to apply further whatever you need.
IF you're using an anchor <a>
element as your #btn
than you'd want to prevent the default browser action behavior using event.preventDefault()
(instead of return false;
) like:
$(function(){ // DOM ready shorthand
var arr = ["Hello!", "Hi!", "Hey!", "Aloha!", "Bok!", "Tchuss!"];
$("#btn").text( arr[0] ).click(function( ev ){ // Set initial greet + Click handler.
ev.preventDefault();
arr.push( arr.shift() ); // Push first key to last place...
$(this).text( arr[0] ); // and get always the resulting first one
$("#div").slideToggle(); // What's that for?
});
});
Upvotes: 2
Reputation: 801
you can do some this
$(document).ready(function(){
$("#btn").click(function(){
$(this).text(function(i, text){
$(this).text()=== "Hello!" ? $(this).text("Hii!") : $(this).text("Hello!");
$("#div").slideToggle();
return false;
});
});
});
Upvotes: 0
Reputation: 22480
something like this maybe:
$(document).ready(function(){
$("#btn").click(function(){
var text = $(this).text();
var newText = text == 'Hello!' ? 'Hey!' : 'Hallo!';
$(this).text(newText);
$("#div").slideToggle();
return false;
});
});
Upvotes: 0