Jump to content

JS: onClick return


tinfanide

Recommended Posts

I would like to have the text 'I love dogs!' return after users click once more after it shows the text 'I love cats!'.Is there any way in JS that we can return to its original things?Here's my code (it does not work):

<script>function text(text1,text2)	{	text1 = function text1(){	var text1 = document.getElementById('text');	text1.innerHTML = 'I love dogs!';	}	text2 = function text2(){	var text2 = document.getElementById('text');	text2.innerHTML = 'I love cats!';	}	}</script><span>Javascript</span><div id="text" class="text">I love dogs!</div><input type="button" value="change text" onclick="text(text1,text2);" />

Link to comment
Share on other sites

You're making this much too complicated. Your text function does not need any arguments, and it does not need internal functions. What I'm going to show you is not exactly the solution. It is to show you what a general solution will look like. You make the changes to apply it to your particular situation.

function swap() {   var t1 = "First text";   var t2 = "Second text";   var el = document.getElementById('text');   if (el.innerHTML == t1) {	  el.innerHTML = t2;   }   else {	  el.innerHTML = t1;   }}

Get used to the if-else pattern. It is VERY common in programming.

Link to comment
Share on other sites

You're making this much too complicated. Your text function does not need any arguments, and it does not need internal functions. What I'm going to show you is not exactly the solution. It is to show you what a general solution will look like. You make the changes to apply it to your particular situation.
function swap() {   var t1 = "First text";   var t2 = "Second text";   var el = document.getElementById('text');   if (el.innerHTML == t1) {	  el.innerHTML = t2;   }   else {	  el.innerHTML = t1;   }}

Get used to the if-else pattern. It is VERY common in programming.

Thanks for your wise remarks. As a beginner of JS, I am always making things too difficult myself and sometimes forget some simple JS I've just learnt.Now, how about add styles to Id? If I want my text (before being clicked on) to have the color red, how should I do? (I know CSS can do it, but just wonder how JS can do it)
<script>// originally I did:document.getElementById('text').style.color = 'red';// it did not work, as expected; just no idea of how to make the effect by JSfunction swaptxt(){	text.style.color='red'; // it did change the color but just after JS is run	var txt1 = 'I love dogs!';	var txt2 = 'I love cats!';		var txt = document.getElementById('text');	if (txt.innerHTML == txt1){		txt.innerHTML = txt2;				}	else {		txt.innerHTML = txt1;		}	}</script><div id="text" class="text">I love dogs!</div><input type="button" value="change text" onclick="swaptxt();" />

Link to comment
Share on other sites

This: txt.style.color='red';should come below this: var txt = document.getElementById('text');If it should be only red for dogs (or cats) then put the color statement in the if-structure or the else-structure. Assign a different color in the other structure. That way, if this is what you want, changing the text will also change colors.

Link to comment
Share on other sites

@Tin: I'm just teasing thescientist. Keep doing what you're doing.@thescientist :)

var swap_object = {   i: 0,   arr: [	  ['I love dogs!', '#000'],	  ['I love cats!', '#f55']   ],   swap: function (el) {	  el.innerHTML = this.arr[this.i = this.i ? 0 : 1][0]; // I made this annoying terse as a joke. haha	  el.style.color = this.arr[this.i][1];   }};window.onload = function () {   document.getElementById("text").onclick = function () {	  swap_object.swap(this);   }}

Of course, it doesn't scale well.

Link to comment
Share on other sites

@Tin: I'm just teasing thescientist. Keep doing what you're doing.@thescientist :)
var swap_object = {   i: 0,   arr: [	  ['I love dogs!', '#000'],	  ['I love cats!', '#f55']   ],   swap: function (el) {	  el.innerHTML = this.arr[this.i = this.i ? 0 : 1][0];	  el.style.color = this.arr[this.i][1];   }};window.onload = function () {   document.getElementById("text").onclick = function () {	  swap_object.swap(this);   }}

Of course, it doesn't scale well.

Is the script written by you above working like the last script you corrected for me does?
Link to comment
Share on other sites

Yes, with the color change added also.BUT if you do not understand how it works, you probably don't want to use it. If you ever need to make any changes, you might not know exactly how to make them, and the result could be a mess.

Link to comment
Share on other sites

Yes, with the color change added also.BUT if you do not understand how it works, you probably don't want to use it. If you ever need to make any changes, you might not know exactly how to make them, and the result could be a mess.
Actually I've tried your script out and found not work.That's why I'd asked.There are many parts I cannot figure out. But I am very eager to analyse it so that I can learn to use it later on.Below is the code I tried:I know something is missing so it just doesn't make sense to JS.Could you kindly point out what I missed?
<script>var swap_object = {   i: 0,   arr: [	  ['I love dogs!', '#000'],	  ['I love cats!', '#f55']   ],   swap: function (el) {	  el.innerHTML = this.arr[this.i = this.i ? 0 : 1][0];	  el.style.color = this.arr[this.i][1];   }};window.onload = function () {   document.getElementById("text").onclick = function () {	  swap_object.swap(this);   }}</script><div id="text">I love dogs!</div>

Link to comment
Share on other sites

I forgot about the button in your original. My technique works if you click the text itself. These changes should make the system work with a button instead:

<script type="text/javascript">   var swap_object = {	  i: 0,	  arr: [		 ['I love dogs!', '#000'],		 ['I love cats!', '#f55']	  ],	  swap: function (el) {		 this.i = this.i ? 0 : 1;  // I added this line and changed the one below it to help you understand		 el.innerHTML = this.arr[this.i][0];		 el.style.color = this.arr[this.i][1];	  }   };   window.onload = function () {	  document.getElementById("myButton").onclick = function () {		 swap_object.swap(document.getElementById("text") );	  }   }</script><div id="text">I love dogs!</div><input type="button" value="change text" id="myButton" />

Adding the id to the button is important.Once you get it working, write back with questions. If you are not familiar with Object Oriented Programming, you might want to look here first. It's not a complete tutorial, but it can get you started.I don't know what your skill level is, but this is not a beginner's discussion. I don't mind talking about it, but you should know that.

Link to comment
Share on other sites

I don't know what your skill level is, but this is not a beginner's discussion. I don't mind talking about it, but you should know that.
Skill level = next to 0Just start off learning JS after having some knowledge of html, css and jQuery. But they are far from scripting. So I can hardly understand the logic behind scripting languages. Still analysing the logic behind. I know the logic of html or css is very different from that of JS. That's why when I have been messing up with scripts while burning the midnight oil, I cannot help going here for help.But anyway, I've read the tutorial links given by you. I have particularly been interested in the multi-arrays one, which I have never learnt before. That's why I at the first glance was shocked by the scripts you wrote and claimed it did not work.But now it works well.I've amended it to revise some of the JS codes I've learnt before and come up like this
var swap_object = {   i: 0,   arr: [	  ['I love dogs!' /* array[0][0] */, '#000' /* array[0][1] */],	  ['I love cats!' /* array[1][0] */, '#f55' /* array[1][1] */]   ],   swap: function (el) {	  this.i = this.i ? 0 : 1;  /* this.i = arr[*][*]; here, this.i can either be [0] or [1] */	  el.innerHTML = this.arr[this.i][0];	  el.style.color = this.arr[this.i][1];   } /* up to here, this = swap_object */};function txt_swap(){	document.getElementById("text").onclick = function () {	  swap_object.swap(this);} /* this = (Id)"text" = el */	}function bn_swap(){	document.getElementById("myButton").onclick = function () {	  swap_object.swap(document.getElementById("text"));   }}window.onload = function (){	txt_swap(); bn_swap();	};

After several play-arounds, the only bit I cannot catch up with iswhy can we use : to define a thing in JSI saw you writearr : [...]swap : function(el) {}Are they an defined object?Many thanks for your help. You've been very helpful to my learning of JS.

Link to comment
Share on other sites

Here's a simple object and ways to access the data. I'm using alerts only for demonstration:

var ob = {name: "Dad", child: "Deirdre", food: "pizza"};alert (ob.name); // "Dad"alert (ob['child']); // "Deirdre"var myKey = "food";alert (ob[myKey]); // "pizza"

Each element in the object consists of a key-value pair. Each key is declared in unquoted text. Each value is associated with its key with the : operator. Each pair is separated by a comma. Values can be accessed using dot or bracket notation. Using bracket notation, a key can be passed as a string variable.For programmer clarity, an object can be constructed with white space separating the elements. Here is the same object declared in a more readable fashion:

var ob = {   name: "Dad",   child: "Deirdre",   food: "pizza"};

We can also use dot and/or bracket notation to create an object. Note that each assignment is a unique statement:

var ob = {}; // equivalent to ob = new Object();ob.name = "Dad";ob['child'] = "Deirdre";var myKey = "food";ob[myKey] = "pizza";

And if we want to create an arbitrary number of objects using an object constructor:

function Person (myName, myChild, myFood) {   this.name = myName;   this.child = myChild;   this.food = myFood;};var dad = new Person ("Dad", "Deirdre", "Pizza");alert (dad.food); // "Pizza"var mom = new Person ("Andy", "Opie", "Chicken Tandoor");alert (mom.food); // "Chicken Tandoor"

Note the use of the new and this keywords.Got enough for now? :)

Link to comment
Share on other sites

Already more than I can learn at a time. Marvelous tutorial for me.Object, Key,Operator, Value, Function...Needa be working on them for a week...

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...