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'));
})
})
Related
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>
I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", listenerName);
}
var listener1 = function() {
document.getElementById('demo').innerHtml = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHtml = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHtml = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHtml = "4";
}
</script>
</body>
</html>
Unfortunately, it doesn't work. What's up with that? Thank you.
There are 3 issues with your code:
In your for loop, you are essentially attaching strings as eventlisteners. You need to access your event listeners from the string you have.
Since you eventlisteners are declared in the global scopre, you can use window to access them:
button.addEventListener("click", window[listenerName]);
You are attaching the event listeners before declaring them. You need to declare listener1 and so on before your for loop
innerHtml does not exist. The right syntax is innerHTML
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var listener1 = function() {
document.getElementById('demo').innerHTML = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHTML = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHTML = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHTML = "4";
}
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", window[listenerName]);
}
</script>
</body>
</html>
your line button.addEventListener("click", listenerName); tried to add a function called listenerName to the click event, and since listenerName is a variable and not a function, it doesn't work.
You could use an array of function to make it work instead.
var array_of_functions = [
'listener1' : listener1,
'listener2' : listener2,
'listener3' : listener3,
'listener4' : listener4
]
and then in your loop you could create the listener by giving the right function:
button.addEventListener("click", array_of_functions[listenerName]);
Also, make sure you create the function and the array before running the loop or they won't exist yet when the code runs.
There's a slightly easier way to do this - just have one function that handles the event:
for (var button of allButtons) {
button.addEventListener("click", handleClick, false);
}
function handleClick() {
var id = this.id.match(/button-listener(\d)/)[1];
document.getElementById('demo').innerHTML = id;
}
DEMO
Or, you can change your loop like this and your code will work
allButtons.forEach(function (button, i) {
var listenerName = button.id.slice(button.id.lastIndexOf("-") + 1);
button.addEventListener("click", function () {
document.getElementById('demo').innerHTML = i + 1;
});
});
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.
How can you pass a string via proxy when binding event handlers? I want to pass a data attribute that is attached to the target handler to a method of an object. Is this possible?
function ReservationSchedulePicker(reservationType){
//Reservation Type Accepted Use: 'routine' || 'vacation'
this.reservationType = reservationType;
//DIV for Schedule Picker
this.schedulePickerDiv = $("#schedulePicker");
//Add Event Handler to Anchor
$(this.schedulePickerDiv).on( "click", "#addWalk", $.proxy(this.openAddWalkDialog, this));
}
}
ReservationSchedulePicker.prototype.openAddWalkDialog = function(event, day) {
//Trying to pass the data-day value to this function using proxy
}
//I need the data-day value inside of openAddWalkDialog Is this possible?
<a href="#" id="addWalk" data-day="monday">
Is this what you are looking for:
<script type="text/javascript">
function ReservationSchedulePicker(reservationType){
this.reservationType = reservationType;
this.schedulePickerDiv = $("#schedulePicker");
this.schedulePickerDiv.on( "click", "#addWalk", $.proxy(this.openAddWalkDialog, this));
}
ReservationSchedulePicker.prototype.openAddWalkDialog = function(event) {
event.preventDefault();
alert(this.reservationType);
}
$(document).on('ready',function(){
var x = new ReservationSchedulePicker('hello world');
});
</script>
<div id="schedulePicker">
Hello
</div>
Update 1: Based additional details provided in comments
<script type="text/javascript">
function ReservationSchedulePicker(reservationType){
this.reservationType = reservationType;
this.schedulePickerDiv = $("#schedulePicker");
this.schedulePickerDiv.on( "click", "#addWalk", $.proxy(this.openAddWalkDialog, this, $("#addWalk").attr('data-day') ));
}
ReservationSchedulePicker.prototype.openAddWalkDialog = function(attr, event) {
event.preventDefault();
alert(this.reservationType + '=>'+ attr);
}
$(document).on('ready',function(){
var x = new ReservationSchedulePicker('hello world');
});
</script>
<div id="schedulePicker">
Hello
</div>
Update 2
<script type="text/javascript">
function ReservationSchedulePicker(reservationType){
this.reservationType = reservationType;
this.schedulePickerDiv = $("#schedulePicker");
this.schedulePickerDiv.on( "click", "#addWalk", $.proxy(this.openAddWalkDialog, this ));
}
ReservationSchedulePicker.prototype.openAddWalkDialog = function( event) {
event.preventDefault();
alert(this.reservationType + '=>'+ ($(event.target).data('day'))) ;
}
$(document).on('ready',function(){
var x = new ReservationSchedulePicker('hello world');
});
</script>
<div id="schedulePicker">
Hello
</div>
What about something like reference arguments to proxy:
$(this.schedulePickerDiv).on('click', '#addWalk', $.proxy(this.openAddWalkDialog, this, { foo: bar }));
Or on the event.data object (event.data.foo):
$(this.schedulePickerDiv).on('click', '#addWalk', { foo: bar }, $.proxy(this.openAddWalkDialog, this));
This should do the trick:
var that = this;
$(this.schedulePickerDiv).on("click", "#addWalk", function(e){
that.openAddWalkDialog.call(this, e);
});
ReservationSchedulePicker.prototype.openAddWalkDialog = function(event) {
console.log(event, $(this).data('day'));
}
I have html like this:
<div>
<input type="checkbox" id="checkbox", checked="checked"/>
<label for="checkbox">Copy values</label>
</div>
<div>
<input id="source" type="text"/>
</div>
<div>
<input id="target" type="text"/>
</div>
And I'm trying to implement jQuery code to copy value from source input to target one, only when the checkbox is checked. Here's my code:
var checkbox = $("#checkbox");
var source = $("#source");
var target = $("#target");
var bindFunction = function () {
var copyValue = function () {console.log("asd");
target.val(source.val());
}
if (checkbox.is(":checked")) {
source.bind("keyup", copyValue);
}
else {
source.unbind("keyup", copyValue);
}
}
checkbox.bind("change", bindFunction);
bindFunction();
However, it does not work as expected - for some reason the copyValue function doesn't get unbound. What am I doing wrong?
Here's a jsFiddle.
You need to move the copyValue function outside of the bindFunction function.
This is because it was creating a new instance of copyValue each time the checkbox was clicked so the unbind was running against a different function than the one that was originally bound.
var copyValue = function () {
console.log("asd");
target.val(source.val());
}
var bindFunction = function () {
if (checkbox.is(":checked")) {
source.bind("keyup", copyValue);
}
else {
source.unbind("keyup", copyValue);
}
}
checkbox.bind("change", bindFunction);
bindFunction();
http://jsfiddle.net/5b93H/1/