I am a fairly new programmer, and currently am trying to understand OOP from the JS side of things. I have some pretty basic code for a flashing cursor, yet for some reason it isnt working. The page loads, and the cursor just appears onscreen with no changing. The code is below:
<html>
<head>
<title>Cursor</title>
<script src="jquery.js"></script>
<script>
var str = null;
var counter = 0;
var flipFlop = function() {
alert("working");
if(counter === 0) {
document.getElementbyId('console').style.visibility='visible';
counter = 1;
}
else if(counter === 1) {
document.getElementbyId('console').style.visibility='hidden';
counter = 0;
}
else {
//debug alert
alert("function broken.");
}
};
var setIntOnload = function() {
setInterval(function() {
flipFlop();
}, 1000);
};
</script>
</head>
<body onload="setIntOnload()">
<div id="console">
|
</div>
</body>
</html>
Not sure why this isnt working... Help would be appreciated :)
PS First Post :D
Its Working
Change getElementById instead of getElementbyId
Fiddle
You have a typo in your code. Use getElementById instead of getElementbyId. JavaScript variable names (and methods) are case sensitive.
Fiddle: http://jsfiddle.net/FcrQ7/
Always check your browser console in case something in your code is not working. You had the following error:
Uncaught TypeError: Object # has no method 'getElementbyId'
Related
I am currently studying Javascript and came across a problem while practising setInterval() and `clearInterval().
I am writing a timer that will stop as soon as I press on a button. I have a variable in which I start the interval, a function that executes the timer code and writes the current number the timer is on into a div in HTML.
Then I have a getElementById call that writes an onclick into a button with an id of theButton which contains a clearInterval.
The problem is, if I just write the clearInterval right in the end of the code, without an onclick, it works. But as soon as I write it inside an onclick, it doesn't work without even showing a error.
I have tried searching on the internet and the only answer I got was to use a var instead of a let for the variable with the interval, but that didn't work.
var timerVariable = setInterval(theTimer, 1000);
let count = 11;
function theTimer() {
if (count != 0) {
count--;
document.querySelector("div").innerHTML += count;
console.log("its working");
}
}
document.getElementById("theButton").onclick = 'clearInterval(timerVariable)';
The main reason it doesn't work is because you should assign a function reference to onclick, not a string. Your code should look something like this:
document.getElementById("theButton").onclick = function() {
clearInterval(timerVariable);
});
However, taking this a step further, the onclick is no longer considered good practice. A better solution is to attach your events using addEventListener(), like this:
document.querySelector('#theButton').addEventListener('click', () => {
clearInterval(timerVariable);
});
Here's a full working version with the above correction applied. Note that I added an else case to also clear the interval when the count reaches 0. Without this the interval will run infinitely without any purpose.
var timerVariable = setInterval(theTimer, 1000);
let count = 11;
function theTimer() {
if (count != 0) {
count--;
document.querySelector("div").innerHTML += count;
console.log("its working");
} else {
clearInterval(timerVariable);
}
}
document.querySelector("#theButton").addEventListener('click', () => {
clearInterval(timerVariable);
});
<button type="button" id="theButton">Stop</button>
<div></div>
In the Firefox extension, I want to implement a simple toggle switch that will enable/disable an extension. A basic idea is that the change of state will be saved as a boolean into browser (sync) storage. The state should be read every time, so an extension will know if should work or not.
But - my Javascript knowledge is so poor that I came into trouble.
Here is simple HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form id="form" class="ps-3 mt-3">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="flexSwitch">
<label class="form-check-label" for="flexSwitch">Plugin ON/OFF</label>
</div>
</form>
<label id="test"></label>
<br>
<script src="options.js"></script>
</body>
</html>
And here is a simple JS file:
function CheckAndSave()
{
var state = document.getElementById("flexSwitch");
if(state.checked)
{
document.getElementById('test').innerHTML = 'ON';
browser.storage.sync.set({ delovanje: 1 });
}
else
{
document.getElementById('test').innerHTML = 'OFF';
browser.storage.sync.set({ delovanje: 0 });
}
restoreState();
}
function restoreState()
{
//browser.storage.sync.get("delovanje", function(items) { console.log(items)});
let getting4 = browser.storage.sync.get("delovanje");
getting4.then(setCurrentChoice, onError);
function onError(error) {
console.log(`Error: ${error}`);
}
function setCurrentChoice()
{
var toggle = document.getElementsByName("flexSwitch");
if (result.delovanje === 1)
toggle.checked = true;
else
toggle.checked = false;
}
}
document.addEventListener("DOMContentLoaded", restoreState);
document.getElementById("flexSwitch").addEventListener('change', CheckAndSave);
What is wrong with my code? Is my way of saving Boolean ok?
I tried to write to the console for "debugging", but I don't know how to do it - this is a pop-up after a user press an icon, and nothing is shown in the console.
Most of all you did a mistake here:
function setCurrentChoice(result)
{
var toggle = document.getElementsByName("flexSwitch");
if (result.delovanje === 1)
toggle.checked = true;
else
toggle.checked = false;
}
In this case, toggle will be array like object, but not the element you expect.
You should use document.getElementById("flexSwitch") as previously.
Another issue that you missed an argument in the setCurrentChoice function. It should take settings like this:
function setCurrentChoice(result){...}
I would also suggest to hide the logic of getting element behind the scene by either wrapping it to the function:
const getToggle = () => document.getElementById("flexSwitch")
Or even move it to the separate class and encapsulate all logic there:
class Toggle {
constructor() {
this._el = document.getElementById("flexSwitch");
}
setCheck(value) {
this._el.checked = value;
}
}
Here is the working sample:
function CheckAndSave()
{
var state = document.getElementById("flexSwitch");
if(state.checked)
{
document.getElementById('test').innerHTML = 'ON';
chrome.storage.sync.set({ delovanje: 1 });
}
else
{
document.getElementById('test').innerHTML = 'OFF';
chrome.storage.sync.set({ delovanje: 0 });
}
}
function restoreState()
{
chrome.storage.sync.get("delovanje",setCurrentChoice );
function setCurrentChoice(result)
{
var toggle = document.getElementById("flexSwitch");
if (result.delovanje === 1)
toggle.checked = true;
else
toggle.checked = false;
}
}
document.addEventListener("DOMContentLoaded", restoreState);
document.getElementById("flexSwitch").addEventListener('change', CheckAndSave);
This approach will help you reduce the code and accidental mistakes.
P.S. Here is how I worked with the storage
The code seems okay, while there are some things I would change (for refactoring purposes to match my flavour) I think it should be working without much issue.
In any case verify the following.
The browser.storage.sync API is only available from extensions, so check that the HTML and JS that you are posting are actually part of the extension that you are using.
The manifest.json is what tells the browser what resources can your extension access, verify that you did add the "storage" permission on there here you can read more about it for chrome, though it will be the same for other browsers
For debugging purposes always remember that the browser lets you have great tools. Read more about developer tools, but as a starter I would tell you to open them and put a debugger statement there where you feel like there's something that isn't working as expected. And then with the console start looking for the properties that you are not finding.
To log items to the console use console.log('XXX') and it should show what you want
I think the problem is that the change event is not fired when setting toggle.checked with JavaScript. Just call CheckAndSave(); from the end of setCurrentChoice.
I know this has been covered extensively as separate issues; I've tried copying verified answers, but I'm having trouble homologating Javascript conditional statements and a link URL change.
Essentially, what I need to do is detect mobile users and change a conference call URL to a tel link. I've been using if (screen.width <=699) { as the condition and it works on redirects. Here's what I've tried:
<script type="text/javascript">
<!--
var call=document.getElementByID('phone');
if (screen.width <= 699) {
call.write('<a href="tel:!PHONENUMBER!">');
else
call.write('<a href="!URL!" target="blank">);
}
//--!>
</script>
</head><body>
...
...
I've also tried these with corresponding else statements to no avail:
no var and document.getElementByID('phone').write
onclick = function() { window.location.href ='tel:!PHONENUMBER!};.
call.src.replace('tel:!PHONENUMBER!');
call.setAttribute("href",'tel:!PHONENUMBER!');
I apologize if this is a super basic issue - I'm still learning Javascript. Thank you in advance.
Will
You need to either wait for the page to finish loading before you execute your JavaScript or move your script block to the bottom of the HTML.
If you want to wait for the page to finish loading, then wrap your code in the following:
window.onload = function () {
// your code goes here
}
Figured it out with help from #sepbot.
<body onload="mobileURL()">
<div id="phone"></div>
<script type="text/javascript">
function mobileURL() {
var a = document.createElement("a");
a.innerHTML="!LINKTEXT!";
var myPhone = document.getElementById('phone');
if (screen.width <= 699) {
a.setAttribute('href', '!TELEPHONE!');
myPhone.appendChild(a);
} else {
a.setAttribute('href', '!URL!');
myPhone.appendChild(a);
}
}
</script>
I can't get the value from a variable by javascript and this don't appear in the code
I don't know how to search about it or to resolve this. My textbox don't alter the color, but receive the color and is not the cache.
Thinking in a better way to make my code works I have developed the function:
<script type="text/javascript">
function checkBatchQTD() {
var element = document.getElementById('<%=txtlblBatchQTD.ClientID%>');
var varValue = element.value;
if (varValue == "") {
element.style.backgroundColor = "#ffffc0";
}
else {
element.style.backgroundColor = "#ffffff";
}
}
</script>
And after do it I have searched for a way to make the function repeat and I have found the window.setInterval to make that function work with repeat:
<script>
window.setInterval(function () {
checkddlProduct();
checkBatchQTD();
checkDate();
}, 500);
</script>
I'm so sorry if I don't have formated the question or not posted the code before this, but I thank you very much for the help.
I've spent the last few hours trying to find the answer to this, but nothing seems to work...
I need to execute a piece of code when a div (or anything inside of it; including iframe content) is clicked. The following code should do it (when added into the div tag), but it doesn't seem to work.
onclick="if(typeof(_vis_opt_top_initialize) =='function'){ _vis_opt_goal_conversion(200); _vis_opt_pause(500);}"
The purpose is to execute a custom conversion goal:
<script type="text/javascript">
if(typeof(_vis_opt_top_initialize) == "function") {
_vis_opt_goal_conversion(200);
}
</script>
Any help will be greatly appreciated :)
I hate using inline js... hate it...
If you need to account for IE (<8), then you can't use addEventListener, so you can do something like this:
function bindListener(el,eventName,eventHandler) {
if (el.addEventListener) { // Anything but IE <8
el.addEventListener(eventName,eventHandler,false);
} else if (el.attachEvent) { // For IE <8
el.attachEvent('on'+eventName,eventHandler);
}
}
Then you can call it using something like this:
var ele = document.getElementById('idOfElement');
bindListener(ele, 'click', functionToCall);
Try using addEventListener. Link here. The Example on that page is exactly what you are asking for.
First give your div a unique ID
<div id="yourDivID"></div>
then set the onclick function in window.onload
var yourDiv = document.getElementById("yourDivID");
yourDiv.onclick = function() {
if(typeof(_vis_opt_top_initialize) == "function") {
_vis_opt_goal_conversion(200);
}
}
}
I write simple example for you:(j Query answer)
Html Code
<div class="test">Click</div>
JavaScript Code
$('div.test').click(function(){
alert("some");
});
Demo
Edited
JavaScript example
<html >
<script type="text/javascript">
function AttachAllDivEvents()
{
var divCollection = document.getElementsByTagName("div");
for (var i=0; i<divCollection.length; i++)
{
AttachDivClickEvent(divCollection[i]);
}
}
function AttachDivClickEvent(divObj)
{
divObj.onclick = function()
{
document.getElementById("count").innerHTML = parseInt(document.getElementById("count").innerHTML) + 1;
};
}
window.onload = AttachAllDivEvents;
</script>
<body>
<div>click</div>
<p id="count" style="font:bold 20px Times;color:red;text-indent:20px">1</p>
</body>
</html>