i'm beginner in jQuery Plugin's coding.
I've coded a plugin to generate a Gantt's calendar but i can't succeed with interacting with it.
The code is too long to be posted so i've coded a sample of what a need in kind of interaction.
Here is a sample code that generate a counter and two buttons to increase or decrease the value of the counter.
So the question is : How can i make the button increase / decrease the counter and of course refresh display.
Thanks,
[EDIT]
I explain again what i want to do :
- The buttons are generated by the plugin.
- When they are clicked, they increase/decrease the value and refresh display
- I dont want an external action binding.
- The plugin must be standalone
[/EDIT]
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2">
<title></title>
<link rel="stylesheet" href="/styles/jquery-ui.css" type="text/css">
<script src="/scripts/jquery.js"></script>
<script src="/scripts/jquery-ui.js"></script>
<script>
(function($){
$.fn.mySample = function() {
var _myCount = 0;
this.initialize = function ()
{
this.html('<input type="button" value="--">Count : ' + _myCount + '<input type="button" value="++">');
}
return this.initialize();
}
})(jQuery);
$(document).ready(
function()
{
$('#myDiv').mySample();
}
);
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
Sorry for my first answer :)
So here is your mySample plugin working as a standalone
http://jsfiddle.net/P4p3m/2/
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2">
<title></title>
<script src="jquery-1.11.0.min.js"></script>
<script>
(function($){
$.fn.mySample = function() {
this._counter = 0; // Your counter
this.initialize = function (config)
{
// Get the context of the outside
var context = this;
// Init the -- button
var inputMinus = document.createElement("input");
inputMinus.type = "button";
inputMinus.value = "--";
$(inputMinus).click(function(){
context.updateCounter(-1);
});
this.append(inputMinus);
// Init the display
var spanDisplay = document.createElement("span");
context.spanDisplay = spanDisplay;
$(spanDisplay).text(context._counter);
this.append(spanDisplay);
// Init the ++ button
var inputPlus = document.createElement("input");
inputPlus.type = "button";
inputPlus.value = "++";
$(inputPlus).click(function(){
context.updateCounter(+1);
});
this.append(inputPlus);
}
// Updating the counter value and the display
this.updateCounter = function(nbr){
this._counter += nbr;
$(this.spanDisplay).html(this._counter);
};
// Start the plugin
return this.initialize();
}
})(jQuery);
$(document).ready(
function()
{
$('#myDiv').mySample();
}
);
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
I modified your code to add id's to better identify the buttons and a span to identify where we want to modify the count:
Here's the updated code to reflect your comments, along with the code working in a fiddle: http://jsfiddle.net/XMgz4/
(function ($) {
$.fn.mySample = function () {
var _myCount = 0;
var inputStr = '<input id="decButton" type="button" value="--">'
+ 'Count : <span id="count">' + _myCount
+ '</span><input id="incButton" type="button" value="++">';
this.html(inputStr);
this.find("#decButton").on("click", function() {
_myCount --;
$("#count").text(_myCount);
});
this.find("#incButton").on("click", function() {
_myCount ++;
$("#count").text(_myCount);
});
}
})(jQuery);
You will need to put the Count : ' + _myCount + ' inside an element.. like this:
'Count : <div id="result">' + _myCount + '</div>'
After that you will create a function to get the value of result.. like this $('#result').html()
and increase or decrease the value using onclick event of your inputs... (You must to add class or id for your inputs...)
I will suppose that the id is btnDecrease and btnIncrease... You will need to do something like this:
$('#btnDecrease').on('click', function(){
$('#result').html(parseInt($('#result').html()) - 1);
});
and
$('#btnIncrease').on('click', function(){
$('#result').html(parseInt($('#result').html()) + 1);
});
Hope it helps
Related
I am trying to create a simple Chrome Plugin - however I have come to an issue.
I am trying to detect a click on a div using a simple getElementById - however as the api call happens after the DOM is loaded the JS cannot 'find' any div's and gives an error and doesn't do anything after I click on the element.
How do I detect the click, after the data from the API has loaded? I have included some of my code below:
Thanks
document.addEventListener('DOMContentLoaded', function () {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function () {
inputBox = document.getElementById("postcodeInput").value
console.log(inputBox)
let xml = new XMLHttpRequest();
xml.open('get', "https://api.getaddress.io/find/" + inputBox + "/?api-key=SECRET&expand=true", false);
xml.send(null);
var data = xml
var arr = xml.responseText
var data = JSON.parse(arr)
var postcode = data.postcode
var addresses = data.addresses
console.log(addresses)
document.getElementById("postcode").innerHTML = postcode;
var text = "";
var i;
for (i = 0; i < addresses.length; i++) {
text += "<div id='addressClick' name=" + i + ">" + addresses[i].line_1 + "</div>" + "<br>";
}
document.getElementById("data").innerHTML = text;
clickFunc()
}, false);
}, false);
function clickFunc() {
var rowBox = document.getElementById("addressClick");
rowBox.addEventListener('click', function () {
console.log('asd');
}, true);
}
HTML
<!doctype html>
<html>
<head>
<title>Address Search</title>
<script src="popup.js"></script>
</head>
<body>
<h3>Address Search</h3>
<input type="text" id='postcodeInput' name="postcodeInput" value="KW1 4YT">
<button id="checkPage">Search</button>
<div class='results'>
<h3>Results - <span id='postcode'></span></h3>
<p id='data'></p>
</div>
</body>
</html>
<style>
body {
width: 200px
}
#addressClick:hover {
color: blue;
cursor: pointer
}
</style>
You can attach an EventListener to all the body and, at every click, detect if the clicked element is the desired one:
document.body.addEventListener('click', event => window.alert(event.target.innerText));
This can sound like an aggressive solution, but it's way less invasive than a MutationObserver
I am having a JavaScript code that is having a value in #message but i have not defined anywhere.
Does $("#message").html(result); is something inbuilt in Javascript?
I apologize if it is very basic and stupid question.
It is linked to my another question "
https://stackoverflow.com/questions/41745209/save-javascript-value-when-converting-speech-to-text-via-webkitspeechrecognition#
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="Content/SpeechScript.js"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body >
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<script type="text/javascript">
function Typer(callback) {
speak('Welcome ,Please Speak your CPR Number');
var srcText = 'WelcomeToDanske,PleaseSpeakyourCPR Numberwhat';
var i = 0;
debugger;
var result = srcText[i];
var interval = setInterval(function () {
if (i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
debugger;
document.getElementById('user').innerHTML = result;
// var parent = document.getElementById('parentDiv');
// var text = document.createTextNode('the text');
// var child = document.getElementById('parent');
// child.parentNode.insertBefore(text, child);
// var div = document.getElementById('childDiv');
//var parent = document.getElementById('parentDiv');
//var sibling = document.getElementById('childDiv');
////var text = document.createTextNode('new text');
// //parent.insertBefore(result, sibling);
},
100);
return true;
}
function playBGM() {
startDictation(event);
}
Typer(function () {
playBGM();
});
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
</script>
</div>
<div id="clockDisplay">
<span id="id1">Welcome:</span>
<table width="100%" border="1"><tr><td width="50%"> Username : </td><td><div id="message"></div></td></tr></table>
</body>
</html>
$("#message").html(result); is something inbuilt in Javascript?
No.
$ is a variable that is no part of the JavaScript spec, nor is it part of the common extensions to JS provided by browsers in webpages. It is commonly used by libraries such as PrototypeJS and jQuery. This particular case looks like jQuery, but you aren't including that library in your page.
Fist off, remember to include jQuery as script in your html document or $ will not be defined.
#message Refers to an element in your html document with the tag of id="message"
To get an element in jQuery, by id, you use this syntax: var Element = $("#ID");
So, to make sure your code works, ensure that both there is an element with the ID message, and a defined variable named result containing the html text to put into your element.
Since you want to append to <div id="clockDisplay"> <span id="user">Username :</span></div>, why not change it to:
<div id="clockDisplay">
<span id="user">Username :</span>
<div id="message"></div>
</div>
Please note that I am not using classes. I haven't found an answer for this SPECIFIC question.
Using javascript, how can I program a button to change the stylesheet each time the button is clicked?
I've tried different if, else if and else, but when I try them, it breaks the code (ie, it will change the color to blue if red, but not back again).
It works with 2 buttons, but getting it to change each time a single button is clicked seems to be eluding me. I got feed up and programmed a second button to change it back.
This works for 2 buttons:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
<style>
</style>
</head>
<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>
<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"}
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"}
}
</script>
</body>
I would like to be able to get rid of the second button and second function and have it all with one button.
EDIT...
I tried this, and it failed.
function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"};
else {document.getElementById("um").href = "stylesheet1.css"}
}
Make sure you're using == instead of = for your comparisons!
if (document.getElementById("um").href == "stylesheet1.css")
etc
Try this:
<button id="x" onclick="myFunction()">Change</button>
<script>
function myFunction() {
var link = document.getElementById("um");
var segments = link.href.split('/');
var currentStyle = segments[segments.length - 1];
var style = (currentStyle == 'stylesheet1.css') ? 'stylesheet2'
: 'stylesheet1';
document.getElementById("um").href = style + ".css"
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
</head>
<body>
<p>booga</p>
<button onclick="myFunction('um','stylesheet1.css', 'stylesheet2.css')">swap</button>
<script>
function myFunction(id,a,b) {
var el = document.getElementById(id);
var hrefStr;
if(~el.href.indexOf(a)) {
hrefStr = el.href.replace(a, b);
el.href = hrefStr;
} else {
hrefStr = el.href.replace(b, a);
el.href = hrefStr;
}
}
</script>
</body>
</html>
HTML code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="score-board.css">
<title>Score Board App</title>
</head>
<body>
<div id="playersscores">
<span id="p1score">0</span><span> To </span> <span id="p2score">0</span>
</div>
<p>Playing to <span id="score">5</span></p>
<input type="field" value="5" ></input>
<button id="p1clicked">Player one</button>
<button id="p2clicked">Player two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score-board.js"></script>
</body>
</html>
Javascript is :
Whenever this code is loaded :
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score (player_result) {
//var score = parseInt(player_result.innerText) + 1;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener("onclick", increment_score(p1result))
Whenever this code is loaded in a browser, the span showing the result for player 1 is showing one directly without clicking on player 1 button. i'm not sure what is wrong with the event listener im using.
The event is click instead of onclick
The event listener should be a reference to the function itself, not the result of a function call (which increments the score by 1)
Inside the function, you can access the button with this:
The code could look like this:
function increment_score() {
var player_result = this;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener('click', increment_score);
Use click event not onclick
You pass result of function not instead reference to function
If you need pass parameters to event handler - you can use bind:
p1clicked.addEventListener("click", increment_score.bind({result: p1result, inc: 1 }) )
p2clicked.addEventListener("click", increment_score.bind({result: p2result, inc: 2 }) )
function increment_score () {
var score = parseInt(this.result.innerText) + this.inc;
this.result.innerText = score;
}
[ https://jsfiddle.net/6vw8ay3x/ ]
You have a couple problems there. First, when calling the addEventListener function, you need to specify just "click", not "onclick". Secondly, when you pass the function to addEventListener, you just want it to be a reference to the function not an actual function call. The following changes will net you the result you are seeking.
function increment_score () {
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
}
p1clicked.addEventListener("click", increment_score);
But since you want to be able to use the same function for multiple players, then I would suggest adding the "onclick" handler to the HTML which will allow you to pass the element you want to increment. Then your HTML code would look like this:
<button id="p1clicked" onclick="increment_score_with_param(p1result);">Player one</button>
<button id="p2clicked" onclick="increment_score_with_param(p2result);">Player two</button>
and your javascript would be:
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score_with_param (player_result) {
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
window.onload = function(){
var p1result = document.querySelector('#p1score');
var p2result = document.querySelector('#p2score');
var p1clicked = document.querySelector('#p1clicked');
p1clicked.addEventListener("click", function(e){
e.preventDefault();
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
});
}
I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
The HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.
onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
UPDATE
Instead of using main(), use DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
Call the main function at the end of your body content
You are getting this error just because the element dose not exists at the time of its selection by JS DOM
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>