I'd like to do the following. I got a button like this:
<button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button>
The JS part is this:
var search = new SiteSearch();
Now I'd like to do this:
Once clicked, the label of the button should show Stop search. And the called function should be search.stop(). If the user clicks Stop search, the button should be the Start search button again.
How can I do this in an elegant way?
Here you have working code snippet for this:
$(document).ready(function() {
function startSearch() {
console.log('Here your start search procedure');
}
function stopSearch() {
console.log('Here your stop search procedure');
}
$('.search-button').click(function() {
var buttonSelector = '.search-button';
if($(buttonSelector).hasClass('searching')) {
$(buttonSelector).removeClass('searching');
$(buttonSelector).text('Start search');
stopSearch();
} else {
$(buttonSelector).addClass('searching');
$(buttonSelector).text('Stop search');
startSearch();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="uk-button uk-position-bottom search-button">Start search</button>
Here's what I'd do: add an ID to the button, then query that button in the script and add a click listener to it. The script would keep track of whether or not a search is being done, then call search.start/stop() and set the button text accordingly.
<button id="search-button" class="uk-button uk-position-bottom">
Start search
</button>
<script>
const search = new SiteSearch()
const searchButton = document.querySelector('#search-button')
let searching = false
searchButton.addEventListener('click', () => {
if (!searching) {
search.start()
searching = true
searchButton.textContent = 'Stop search'
} else {
search.stop()
searching = false
searchButton.textContent = 'Start search'
}
})
</script>
You can do this easily like below:
var $elem = $('.uk-button.uk-position-bottom');
var search = {
//start function
start: function(){
//change the text
$elem.text('Stop search');
//change the click function
$elem.attr('onclick', 'search.stop()');
console.log('start clicked');
},
//stop function
stop: function(){
//change the text
$elem.text('Start search');
//change the click function
$elem.attr('onclick', 'search.start()');
console.log('stop clicked');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button>
i think this answer is the same as a previus posted question:
https://stackoverflow.com/a/10671201/7387232
with the little add that when the button is clicked the button has to change the onclick propriety maybe with a check
object.onclick = function() {
if(search.isRunning()) search.stop();
}
and viceversa :-)
Try this:
Html:
<button id="search-btn" "class="uk-button uk-position-bottom" onclick="toggleSearch()">Start search</button>
JS:
var searching = false;
function toggleSearch(){
if(searching){
search.stop();
document.getelementbyid("search-btn").innerHTML = "Start search";
}else{
search.start();
document.getelementbyid("search-btn").innerHTML = "Stop search";
}
searching = !searching;
}
If I understood correctly your question this will solve your problem:
<button class="uk-button uk-position-bottom" data-process="0">Start search</button>
<script>
$(".uk-button").click(function () {
var $this = $(this);
var processStatus = $this.data("process");
//var search = new SiteSearch();
if (processStatus == "0") {
//you can trigger start function
$this.data("process", "1");
$this.text("Stop Search");
}
else if (processStatus == "1") {
//you can trigger stop function
$this.data("process", "0");
$this.text("Start Search");
}
});
</script>
Related
I have an html button where I change the value and id in an attempt to execute a javascript function based on the new ID.
From this;
<button id="Start" class="Button">Start</button>
to this;
<button id="Stop" class="Button">Stop</button>
The intent is for the user to click on the Start button to execute the associated function and change the existing button into a Stop button to execute its associated function. One button with two separate tasks.
var mySocket = new WebSocket("ws://192.168.1.102:5678/");
window.onload = function() {
var StartST = document.getElementById('Start');
var StopST = document.getElementById('Stop');
var socketStatus = document.getElementById('usercontent');
if (StartST) {
StartST.addEventListener("click", function (e) {
StartST.innerHTML = "Stop";
StartST.id = "Stop";
mySocket.send('start');
socketStatus.insertAdjacentHTML('afterbegin','<div class="received">Start -> ' + StartST.id + '</div>\n');
e.preventDefault();
})
}
if (StopST) {
StopST.addEventListener("click", function (e) {
mySocket.send('stop');
StopST.innerHTML = "Start";
StopST.id = "Start";
socketStatus.insertAdjacentHTML('afterbegin','<div class="received">Stop</div>\n');
e.preventDefault();
})
}
};
The issue is I cannot execute the Stop button function and I am not sure how to implement delegation to get it to work correctly.
Currently have code in HTML, but would like to convert it to JavaScript. You can see the codes below:
I'd like to convert the following to JQuery (instead of in HTML):
<button id="1" onclick="swapStyleSheet('style1.css')">Button1</button>
<button id="2" onclick="swapStyleSheet('style2.css')">Button2</button>
<button id="3" onclick="swapStyleSheet('style3.css')">Button3</button>
The above code triggers this:
var swapStyleSheet = function (sheet) {
document.getElementById('pagestyle').setAttribute('href', sheet);
storebackground(sheet);
}
var storebackground = function (swapstylesheet) {
localStorage.setItem("sheetKey", swapstylesheet); //you need to give a key and value
}
var loadbackground = function () {
document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
}
window.onload = loadbackground();
Thanks!
You could try something like this..
// Here we get all the buttons
var button = document.getElementsByTagName('button');
// We loop the buttons
for (var i=0; i<button.length; i++){
// Here we add a click event for each buttons
button[i].onclick = function() {
alert("style"+this.id+".css");
//swapStyleSheet("style"+this.id+".css"); you can do it something like that;
}
}
var swapStyleSheet = function (sheet) {
//document.getElementById('pagestyle').setAttribute('href', sheet);
//storebackground(sheet);
}
var storebackground = function (swapstylesheet) {
// localStorage.setItem("sheetKey", swapstylesheet); //you need to give a key and value
}
var loadbackground = function () {
//document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
}
//window.onload = loadbackground();
<button id="1">Button1</button>
<button id="2" >Button2</button>
<button id="3" >Button3</button>
No need for JQuery
Looks like you are just looking for click event handlers. Here's a version using jQuery. I commented out the code dealing with the missing 'pagestyle' element and localstorage to prevent js errors in the StackOverflow snippet.
var swapStyleSheet = function (sheet) {
console.log( 'sheet: ' + sheet ); // look at the console when you press a button
//document.getElementById('pagestyle').setAttribute('href', sheet);
//storebackground(sheet);
}
var storebackground = function (swapstylesheet) {
//localStorage.setItem("sheetKey", swapstylesheet); //you need to give a key and value
}
var loadbackground = function () {
//document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
}
window.onload = loadbackground();
$( '#1' ).on( 'click', function() {
swapStyleSheet('style1.css');
});
$( '#2' ).on( 'click', function() {
swapStyleSheet('style2.css');
});
$( '#3' ).on( 'click', function() {
swapStyleSheet('style3.css');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1">Button1</button>
<button id="2">Button2</button>
<button id="3">Button3</button>
<button id="1" class='changestyle' data-stylesheet = "style1.css">Button1</button>
<button id="2" class='changestyle' data-stylesheet = "style2.css">Button2</button>
<button id="3" class='changestyle' data-stylesheet = "style3.css">Button3</button>
jQuery
$(function(){
$(".changestyle").on("click", function(){
$("#pagestyle").attr("href", $(this).data('stylesheet'));
})
})
I wrote the function for check if button was clicked twice and if it was to measure the time between two clicks. It has to prevent multiple clicks in short time.
Button click:
$("#Save").click(function () {
dateTime1 = new Date().getTime();
BtnId = this.id;
showSaveDialog();
});
And measuring function:
ButtonWasTriggeredTwice: function () {
var result = false;
var currentTime = new Date().getTime();
var time = currentTime - dateTime1;
if (PreviousBtn === null) {
result= false;
} else {
if (PreviousBtn === BtnId) {
if ( time < 1500) {
result = true;
}
else result = false;
}
else {
result= false;
}
}
PreviousBtn = BtnId;
BtnId = null;
return result;
}
BtnId and PreviosusBtn are global scope variables.
The strange thing is this function works great when I set breakpoints in debugger. If I switch off debugger function blocks every next click on button, no matter what time interval is between clicks
You can use this solution with unbind and timeout, like this:
HTML
<input type="button" id="Save" value="save me" />
JS:
function saveEventButton(){
$("#Save").click(function () {
alert('saved!');
$("#Save").unbind('click');
setTimeout(function(){
saveEventButton();
}, 5000); // 5sec
});
}
saveEventButton();
This is the JSFiddle
UPDATE This solution is a mix from mine and Revish Patel solution
function disableTimeout(_this){
$(_this).prop('disabled','disabled');
setTimeout(function(){
$(_this).prop('disabled','');
}, 5000); // 5sec
}
$("#Save").click(function () {
alert('saved!');
disableTimeout(this);
});
This is the JSfiddle
You can also disable button when you first click is performed.
$(document).ready(function () {
$("#Save").click(function(){
$('#Save').prop('disabled','disabled');
// Perform your button click operation
});
});
I'm new to JS and JQuery and I'm trying implement the following functionality.
I have a form which has multiple inputs, each having its individual validation. These validations have been implemented inside one function.
function checkUpload() {
var flagu1=0;
var bookname = document.getElementById("title").value;
var flagu2=0;
.....
.....
var flagu6=0;
if( flagu1==0 && flagu2==0 && flagu3==0 && flagu4==0 && flagu6==0 )
return true;
else
return false;
}
This validation function is executed when a user clicks on the following button:
<button class="btn btn-secondaryup" name="submit" value="Upload" id="submitmeup" data-loading-text="UPLOADING..." onclick="clearBox('uploaderror')" type="submit" style="width:100%">UPLOAD</button>
Now I'm trying to implement Bootstap's 'loading state button' in this. The functionality would work like this:
When a user clicks on the button, the front-end validation function is called. Once the validation function (checkUpload()) returns true, the following JQuery function should be called.
<script>
$('#submitmeup').click(function() {
var $btn = $(this);
$btn.button('loading');
setTimeout(function () {
$btn.button('reset');
}, 5000);
});
</script>
The trick is that the button loading function has to be called only after the checkUpload function returns true. How do I implement this?
use below code. Use function inside condition .if function returns true then it execute code in side if condition
<script>
$('#submitmeup').click(function() {
var $btn = $(this);
if(checkUpload()){
$btn.button('loading');
setTimeout(function () {
$btn.button('reset');
}, 5000);
}
});
</script>
First remove the onclick attribute from the button:
<button class="btn btn-secondaryup" name="submit" value="Upload" id="submitmeup" data-loading-text="UPLOADING..." type="submit" style="width:100%">UPLOAD</button>
Then define your functions and set .on('click') event handler:
$(function() {
var $submitButton = $('#submitmeup');
// Submit handler
function handleSubmit() {
clearBox('uploaderror');
var uploadValid = checkUpload();
if (uploadValid) {
// Upload successful
showButtonLoading();
}
}
function showButtonLoading() {
$submitButton.button('loading');
setTimeout(function () {
$submitButton.button('reset');
}, 5000);
}
function checkUpload() {
var flagu1=0;
var bookname = document.getElementById("title").value;
var flagu2=0;
.....
.....
var flagu6=0;
if( flagu1==0 && flagu2==0 && flagu3==0 && flagu4==0 && flagu6==0 )
return true;
else
return false;
}
function clearBox(type) {
// Your implementation here
}
// Event handler
$submitButton.on('click', handleSubmit);
});
Now, clicking the button will go to handleSubmit function, which employs your code.
I noticed my users sometimes click the buttons twice, maybe no one told them one click is enough.
What's the best way to prevent the double-click?
I basically hide the button and show a "loading" gif, but that apparently is not enough...
Usually disabling/hiding/replacing the button should work. If they are real fast, try setting a variable to false when your script starts, return if it's true, set it to true after the first click.
var alReadyClicked = false;
function click(){
if (alreadyClicked)
return false;
alreadyClicked = true;
}
Don't forget to set it to false when the user can click again.
If they are clicking fast enough to fire the double click event, return false.
ondblclick="return false"
EDIT: This will not cancel the single click event so problem would still exist.
I just found out the jQuery funcion .one(), that may be useful great for this kind of purpose! great!
The equivalence to JQuery .one() may be the once option on AddEventListner like:
function doSubmit () { /* your code */ }
btn = document.getElementById ('foo');
btn.addEventListener ('click', doSubmit, {once: true});
Reference: javascript - JS equivalent for jQuery one() - Stack Overflow
Another example using a flag
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test dbl click</title>
</head>
<body>
<button id="btn1">Click Away</button>
<div id="out"></div>
<script type="text/javascript">
function addMessage( msg ){
document.getElementById("out").innerHTML += (new Date().toTimeString()) + " : " + msg + "<br/><br/>";
}
function singleClick(){
addMessage( "single");
}
function addDoubleClickProtection( element, fncToCall ){
var isClicked = false;
var timer = null;
element.onclick = function(){
if(!isClicked){
isClicked = true;
timer = window.setTimeout( function(){ isClicked = false; }, 200);
return fncToCall();
}
}
}
addDoubleClickProtection( document.getElementById("btn1"), singleClick );
</script>
</body>
</html>
Simple method by counting the submit button click and with minimum decoration will:
<script>
var click_count = 0;
function submit_once () {
document.forms.A.elements.cmd.forEach(
function(e,i,l){e.style.color="#888";});
return (click_count++ > 1);
}
function reset_count () {
document.forms.A.elements.cmd.forEach(
function(e,i,l){e.style.color="unset";});
click_count = 0;
}
</script>
<form name="A">
<button type="submit" name="cmd" value="doAdd"
onclick="return submit_once();">Do add</button>
<button type="submit" name="cmd" value="doDel"
onclick="return submit_once();">Do delete</button>
</form>
You can create a util function once which will take CB function. And all logic handles seamlessly. You don't have to create a global variable to count or update.
function once(cb) {
let once = false;
return (...args) => {
!once && cb(...args);
once = true;
};
}
// How to use it.
// Create/bind function
const log = once((data) => {
console.log(data);
});
// Use it
Promise.resolve("hellowold").then(log).then(log);
Above line print only once.