How to make a toggle function - javascript

I’m somewhat new to JavaScript and I made a function that changes text when clicked but how can I make the text change back if you click it again? I would include a screenshot but I don’t have sufficient reputation.

Simple. Just use a toggle variable.
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
var toggle = 0;
function myFunction() {
var el = document.getElementById("demo");
if(toggle == 0){
el.innerHTML = "ZERO";
toggle = 1;
}
else{
el.innerHTML = "ONE";
toggle = 0;
}
}
</script>
Run it Here

the most basic and simplest way is to use three variables-
programming in scala in fun
<script type="text/javascript">
var $elem = $('#para');
var text1 = $elem.text();
var text2 = 'Rust is trending language of 2017';
var toggled = false;
$elem.on('click', function()) {
if(!toggled) {
$elem.text(text2);
toggled = true;
}
else {
$elem.text(text1)
toggled = false;
}
});
</script>

Related

Javascript button toggle

I am trying to write a javascript function so that when a button is clicked, all HTML paragraph elements "p" will be highlighted yellow, the HTML buttons text will then change to "Click to unhighlight" (the code below before the else statement is fully functional, all paragraphs are highlighted and the buttons text changes). I am trying to reload the page using "location.reload();" but it doesn't seem to work.
window.onload = function() {
var button = document.getElementsByTagName("button");
button[0].onclick = changeBackground;
}
function changeBackground() {
var myParas = document.getElementsByTagName("p");
for (var i = 0; i < myParas.length; i++) {
myParas[i].style.backgroundColor = "yellow";
}
var firstClick = true;
var b = document.getElementById("button");
if (firstClick) {
b.innerHTML = "Click to unhighlight";
firstClick = false;
} else {
location.reload();
firstClick = true;
}
}
Any advice on how to properly call the "location.reload();" function would be much appreciated. Thanks in advance.
Your main issue is that you have:
var firstClick = true;
inside the click event handler so every time the button is clicked, it thinks it's the first click. You'd need to have that set outside of the event handler and inside, you'd want to toggle it to the opposite of its current value:
var firstClick = true;
function changeBackground() {
var myParas = document.getElementsByTagName("p");
for (var i = 0; i < myParas.length; i++) {
myParas[i].style.backgroundColor = "yellow";
}
var b = document.getElementById("button");
if (firstClick) {
b.textContent = "Click to unhighlight";
} else {
location.reload();
}
firstClick = !firstClick; // Toggle the first click variable
}
But, really instead of reloading the document, just un-highlight the paragraphs. Reloading takes more resources.
Avoid using getElementsByTagName() as it returns a "live node list", which has performance implications.
Also, rather than set up an explicit onload event handler, just position your code at the bottom of the HTML body.
Lastly, use modern standards for event handling (.addEventListener), rather than event properties (onclick).
See comments inline below:
// Place all this code inside of a `<script>` element and place that
// element at the bottom of the code, just before the closing body tag.
let btn = document.querySelector("button");
// Modern, standards-based way to set up event handlers
btn.addEventListener("click", changeBackground);
function changeBackground() {
// Use .querySelectorAll() and convert the results to an array
var myParas = Array.prototype.slice.call(document.querySelectorAll("p"));
// Loop over all the paragraphs
myParas.forEach(function(par){
// Toggle the CSS class to highlight/or unhighlight them
par.classList.toggle("highlight");
});
// Set the button text accordingly
btn.textContent = myParas[0].classList.contains("highlight") ? "Click to unhighlight" : "Click to highlight";
}
.highlight { background-color:yellow; }
<p>This is a test</p>
<h1>This is a test</h1>
<p>This is a test</p>
<p>This is a test</p>
<div>This is a test</div>
<p>This is a test</p>
<p>This is a test</p>
<button>Click to highlight</button>
the problem is that the else sentence never be call, because the "firstClick" variable always will be true each time you call the changeBackGround method you're setting the variable to true.
to avoid this, just declare the variable out of the method, example:
var firstClick=true;
function changeBackground(){
var myParas = document.getElementsByTagName("p");
for (var i = 0; i < myParas.length; i++) {
myParas[i].style.backgroundColor = "yellow";
}
var b = document.getElementById("button");
if (firstClick){
b.innerHTML = "Click to unhighlight";
firstClick = false;
}else{
location.reload();
firstClick = true;
}
}
A different approach is to use switch case.
<button id="changeButton">Make my paragraphs Yellow</button>
<script>
var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementsByTagName("p");
toggleMe.toggleStatus = "on";
theToggle.onclick = function(){
switch(toggleMe.toggleStatus){
case "on":
toggleMe.toggleStatus="off";
for (var i = 0; i < toggleMe.length; i++) { toggleMe[i].style.backgroundColor = 'yellow'; }
theToggle.textContent = "Make my paragraphs White";
break;
case "off":
toggleMe.toggleStatus="on";
for (var i = 0; i < toggleMe.length; i++) { toggleMe[i].style.backgroundColor = 'white'; }
theToggle.textContent = "Make my paragraphs Yellow";
break;
}
}
</script>
Hope that solve it.

How to make a piece of Javascript work only when the user is on a different tab?

I have the following javascript to make the webpage title change again and again after every five seconds.
<script>
var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
var N = titleArray.length;
var i = 0;
setInterval(func,5000);
function func(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
</script>
I want it to work only when the user has opened a different tab in order to "attract" him/her back to my site.While he/she is on my site I want this javascript to stop working so the title of the webpage is what I simply write in the title tags.
here is a summary of what I want.
<script>
if (the user is not on this tab but has opened and is using a different tab)
{the javascript I have mentioned above};
elce {nothing so the title tags work};
</script>
P.S: Is this a good idea? Got any other suggestions? I just really like thinking out of the box.
Please try with below script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var isActive;
window.onfocus = function () {
isActive = true;
};
window.onblur = function () {
isActive = false;
};
// test
var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
var N = titleArray.length;
var i = 0;
function changeTitle(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
setInterval(function () {
if(window.isActive !== true){
changeTitle();
}
}, 1000);
</script>

Stop incremental counter and disable interaction

I am trying to get the counter to stop at 0 and when it does the entire div is unclickable/disable interaction.
There is a link in the middle. So when i click 3 times I want it to be un-clickable.
edit:also it doesn't need to use Knockout. any approach, if more simple is fine.
What would be the best approach?
Fiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
Simply try adding this line
if (this.numberOfClicks() > 0)
Before
this.numberOfClicks(this.numberOfClicks() - 1);
We'll get something like that:
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
if (this.numberOfClicks() > 0)
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
See Fiddle
A bit late but give a look to my solution because I simplified a lot your code and I think you can get some value from it (for example the use of var self = this which is a best practice).
The idea behind my solution is very simple:
1) Show or hide the link or a normal text with respect to your hasClickedTooManyTimes computed variable.
empty link
<p data-bind='if: hasClickedTooManyTimes'>empty link</p>
2) Simply block the click on div if hasClickedTooManyTimes is true.
self.registerClick = function() {
if(!self.hasClickedTooManyTimes()){
self.numberOfClicks(this.numberOfClicks() - 1);
}
};
Check the Fiddle!
Let me know if this was useful to you!
Just disable the link when your count is done:
First add an id to your link:
<a id="a1" href=#> <p>empty link</p> </a>
Next disable that id when the time is right like this in your javascript:
this.hasClickedTooManyTimes = ko.computed(function() {
if (this.numberOfClicks() < 0) {
$('#a1').attr('disabled', 'disabled'); // <--- disable it
}
return this.numberOfClicks() <= 0;
}, this);
Take a look at the fiddle for JS code, stackoverflow is not validating my code section for the JS content.
HTML
<body>
<div>You have teste clicks!</div>
<div id="demo"></div>
</body>
JS
var btnObserver = (function() {
var me= this;
var clickleft = 3;
var registerClick = function() {
if(clickleft > 0) {
clickleft--;
}
};
var isCLickable = function() {
console.log(clickleft);
return clickleft !== 0;
};
return {
registerClick: registerClick,
isCLickable: isCLickable
}
})();
document.getElementById("mybtn").addEventListener("click", function(){
var message= "Hello World";
btnObserver.registerClick();
if(!btnObserver.isCLickable()) {
message= "X Blocked!";
// return false or do anything you need here
}
document.getElementById("demo").innerHTML = message;
});
Fiddle: http://jsfiddle.net/qkafjmdp/

Javascript onclick() show and onclick() hide

I wanted to make a function with onclick where if I press the div the content should be displayed. If I click on that content it will give me the "starting"-form.
Let me show you the code:
HTML:
<div id="demo">click</div>
Javascript:
var div = document.getElementById("demo");
var info = "This is the information for the user.";
var status = true;
if(status){
div.onclick = function() { div.innerHTML = info };
status=false;
}
else {
div.onclick = function() { div.innerHTML = "click" };
status=true;
}
So I made a variable status that checks what is being shown.
I hope i could express myself good enough. :)
The if statement is not going to magically run again. You need to do the check inside the click. Do not try to bind separate click events.
(function () {
var div = document.getElementById("demo");
var info = "This is the information for the user.";
var status = false;
div.addEventListener("click", function() {
status = !status;
div.innerHTML = status ? info : "click";
});
}());
<div id="demo">click</div>

expand/collapse zk panel with javascript

I wanna click on a ZK's borderlayout(collapsible "East" OR "North" OR...) to open it temporarily with javascript.
what should I do?
thanks in advance buddies.
UPDATE:
When it is closed, by clicking on the closed border area(not on the Open ICON) (Look at the cursor's position in the picture) it will be open temporarily. I want a closed borderLayout and open it like that, with javascript/jquery.
the picture:
1.Get the widget from ZK client engine.
2.call setOpen(true) or setOpen(false)
Here's a sample for this, and also you could test it on ZK fiddle platform.
http://zkfiddle.org/sample/bk3jop/1-Close-border-layout-panel-by-javascript
<zk xmlns:w="client">
<script>
function closeNorth(){
var widget = zk.Widget.$("$mynorth"); //Using the pattern for $ + ID to select a ZK widget.
widget.setOpen(false);
}
function openNorth(){
var widget = zk.Widget.$("$mynorth"); //Using the pattern for $ + ID to select a ZK widget.
widget.setOpen(true);
}
</script>
<button label="click me to close it" w:onClick="closeNorth();" />
<button label="click me to open it" w:onClick="openNorth();" />
<borderlayout >
<north id="mynorth" title="North" maxsize="300" size="50%" splittable="true" collapsible="true">
<div>
Test .... <textbox />
</div>
</north>
</borderlayout>
</zk>
For your purpose ,here I provide another example for this.
http://zkfiddle.org/sample/bk3jop/2-Close-border-layout-panel-by-javascript
<script>
function openNorth(){
var widget = zk.Widget.$("$mynorth"); //Using the pattern for $ + ID to select a ZK widget.
if(!widget.isOpen()){
try{
widget.doClick_({
domTarget:widget.$n('colled')
});
}catch(e){ //ignore unhandled exception.
}
}
}
</script>
Anyway , it's more like a hack.
For more details you could reference to
https://github.com/zkoss/zk/blob/master/zul/src/archive/web/js/zul/layout/LayoutRegion.js
doClick_: function (evt) {
var target = evt.domTarget;
switch (target) {
case this.$n('btn'):
case this.$n('btned'):
case this.$n('splitbtn'):
if (this._isSlide || zk.animating()) return;
if (this.$n('btned') == target) {
var s = this.$n('real').style;
s.visibility = "hidden";
s.display = "";
this._syncSize(true);
s.visibility = "";
s.display = "none";
}
this.setOpen(!this._open);
break;
case this.$n('colled'):
if (this._isSlide) return;
this._isSlide = true;
var real = this.$n('real'),
s = real.style;
s.visibility = "hidden";
s.display = "";
this._syncSize();
this._original = [s.left, s.top];
this._alignTo();
s.zIndex = 100;
if (this.$n('btn'))
this.$n('btn').style.display = "none";
s.visibility = "";
s.display = "none";
zk(real).slideDown(this, {
anchor: this.sanchor,
afterAnima: this.$class.afterSlideDown
});
break;
}
this.$supers('doClick_', arguments);
},

Categories

Resources