window.alert not running when button clicked - javascript

I'm trying to have the message "Parents have been alerted" to display in a window alert screen when a button is clicked, but so far I'm not able to get the message to display.
JS:
var thirtyMinDelayButton = document.querySelector("30-minute-delayed-button");
var hourDelayButton = document.querySelector("hour-delayed-button");
var cancelledButton = document.querySelector("cancelled-button");
/*
* event listeners
*/
thirtyMinDelayButton.onclick = function() {
window.alert("Parents have been alerted");
};
HTML:
<article id="contentstart">
<h2>Football</h2>
<p>Click a button below to update the schedule.</p>
<div class="changes">
<p class="30-minute-delayed-button">30 Minute Delay</p>
<p class="hour-delayed-button">hour Delay</p>
<p class="cancelled-button">Cancelled</p>
</div>
</article>
Why is it that this message isn't displaying, because from what I understand so far of JS it should work.

var thirtyMinDelayButton = document.querySelector(".30-minute-delayed-button");
I had a quick look on the Document.queryselector Mozilla developer site and it looks good, only thing I could see was a period before the class name?
Mozilla Developer Site - QuerySelector

If you want to perform any kind of action on these elements:
var thirtyMinDelayButton = document.querySelector("30-minute-delayed-button");
var hourDelayButton = document.querySelector("hour-delayed-button");
var cancelledButton = document.querySelector("cancelled-button");
Then change them to this:
var thirtyMinDelayButton = document.querySelector(".30-minute-delayed-button");
var hourDelayButton = document.querySelector(".hour-delayed-button");
var cancelledButton = document.querySelector(".cancelled-button");
They are CSS selectors and thus need to have a period before the class name when using document.querySelector

Related

How to add an onclick event in html for Javascript - by a non programmer

This is my first post and I'm asking for help. I am not a programmer of any kind but keen to understand programming and have set up a Codepen page as an example. I am trying to share with some people who have asked can the page allow mouse clicks to work?
What I'm trying to get is to have this working without a keyboard click event, i.e. onkeydown= or onkeyup=, which is what happens now but work with a mouse click which will allow this to work from a mobile phone browser?
If someone can write/show the code I need, I would be very grateful. I see that the HTML needs to define the onclick event and then do two things, the first is speakPrevious and the second getNewRandomColor. I would think that JavaScript will need to define the onclick element? But I am not sure...
`HTML`
<body onkeydown="speakPrevious()">
<body onkeyup="getNewRandomColor()">
`JS`
speakPrevious();
function speakPrevious() {
var synth = window.speechSynthesis;
var utterThis = new SpeechSynthesisUtterance(window.value);
synth.speak(utterThis);
}
getNewRandomColor();
function getNewRandomColor() {
var myArray = ['Red','Green', 'Blue', 'Yellow', ];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementsByTagName("body")[0].style.backgroundColor = rand;
var oldRand = rand;
window.value = oldRand;
}
you can allow users to interact with the web page by either using their keyboard or by clicking on the page if you use an event listener.
In your javascript you can add code (like below) which will trigger the function code whenever the html body element is clicked. This will add functionality to allow users to click on the page.
const page = document.querySelector("body");
page.addEventListener("click", function () {
speakPrevious();
getNewRandomColor();
});
Additionally you may find it easier to combine your body tag events into one body tag with both events.
<body onkeydown="speakPrevious()" onkeyup="getNewRandomColor()">
This will allow the user to either click on the page to trigger the functions or to use a keyboard event.
My final document code looked like this
<html>
<body onkeydown="speakPrevious()" onkeyup="getNewRandomColor()">
<p>The algorithm will select colors at random from RGBY and you may see the same color several times in a row. This
is expected behavior and NOT a fault.<br>Click inside the color and press any keyboard key to move to the next
color.</p>
</body>
<script>
const page = document.querySelector("body");
page.addEventListener("click", function () {
speakPrevious();
getNewRandomColor();
});
function speakPrevious() {
var synth = window.speechSynthesis;
var utterThis = new SpeechSynthesisUtterance(window.value);
synth.speak(utterThis);
}
function getNewRandomColor() {
var myArray = ['Red', 'Green', 'Blue', 'Yellow', ];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementsByTagName("body")[0].style.backgroundColor = rand;
var oldRand = rand;
window.value = oldRand;
}
</script>
</html>

jQuery selector troubles - trying to select and log links

I'm making a Chrome extension that acts on Facebook's newsfeed. I'm trying to select the URL starting with "https://external-ort2-2.xx" from Facebook's "_q7o" div and log it to the console (function capturePic). The earlier code, which inserts a button after the "_q7o" div, works fine, so I think I'm selecting the right div. But URL isn't getting logged.
Many thanks!
function callAttentionToX(jNode) {
var uCW = jNode.closest("div._q7o");
var button = document.createElement("a");
button.innerHTML = "I'm a button";
button.style.float= "left";
uCW.append(button);
}
function capturePic(jNode) {
var uCW = jNode.closest("div._q7o");
var firstHref = $(".uCW a[href^='https://external-ort2-2.xx']").attr("href");
console.log(firstHref);
}
waitForKeyElements("[aria-label$='Story options']", callAttentionToX, capturePic);

Class model for html backend [duplicate]

I'm working on a flexible menu, that does not need to jump from page to page when clicking 'links'.
The JavaScript I use for that is as follows:
var inbox = document.getElementById("u-content-inbox");
var friends = document.getElementById("u-content-friends");
var agenda = document.getElementById("u-content-agenda");
var list = document.getElementById("u-content-list");
var news = document.getElementById("u-content-news");
var notes = document.getElementById("u-content-notes");
function Inbox() {
inbox.style.visibility='visible';
}
function Friends() {
friends.style.visibility='visible';
}
function Agenda() {
agenda.style.visibility='visible';
}
function List() {
list.style.visibility='visible';
}
function News() {
news.style.visibility='visible';
}
function Notes() {
notes.style.visibility='visible';
}
The div elements are like this:
<div id="u-content-inbox" style="visibility:hidden;">
Inbox
</div>
<div id="u-content-friends" style="visibility:hidden;">
Friends
</div>
Each div has a "u-content-x".
However, when I try to change the style attribute "visibility" to visible. It gives me the following error: Uncaught TypeError: Cannot read property 'style' of null
I'm not seeing what I'm doing wrong. Could somebody please bring clearance to me why exactly JavaScript, or rather, I fail to make it work?
Whenever I run a check on
if(!inbox) {
alert("Inbox div has not been found);
}
does not show the alert message.
Make sure you call your javascript after the document is loaded! I'm nearly certain you are trying to get element references before they exist in the dom. The best practices is to put all scripts just before the closing of the body tag.
<script src="some/path/to/file.js"></script>
</body>
If your scripts appear in the document before the elements do, you can put your code inside of this load event function:
window.addEventListener('load', function() {
//your code here
});
Just as a note on your code architecture, you could attach a class to each element and then do this:
var toMakeVisible = document.getElementsByClassName('some-class');
for (var i=0; i<toMakeVisible; ++i) {
var elem = toMakeVisible[i];
elem.style.visibility = 'visible';
}

Dynamically increasing font size

I would like to increase the font size of the paragraph as well as the font size of the number in the button.
I copied and pasted my sizer function from StackOverflow (a few alterations) and thought it would work and still can't get it to work. Can someone help?
Since I've spent so much time on just the first part, as a beginner programmer, I'm wondering what I am missing. Does anyone have any ideas from my code or their experience as to what I might be missing?
Thanks as always.
<html>
<button onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
sizer = function changeFontSize() {
div = document.getElementById("test");
currentFont = div.style.fontSize.replace("pt", "");
div.style.fontSize = parseInt(currentFont) + parseInt(clicks) + "pt";
}
</script>
</html>
Some things here:
I woudn't append two functions to your onclick here. Just append one and call your second function from the first one that gets fired via onclick. That looks a lot more tidy
Don't forget to put var before every variable, without it's not valid JavaScript
I didn't quite understand what you tried with your currentFont variable, so I removed it. It's not necessary and causes the script to not working correctly
<html>
<button onclick='incrementer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
var clicks = 0;
var incrementer = function() {
clicks += 1;
var click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
sizer();
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
div.style.fontSize = parseInt(clicks) + "pt";
}
</script>
</html>
Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window object listening for the load event.
We then store references to the button and the paragraph elements. These are const variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const. The value is returned as a string like "16px" but we need the number, hence the slice and multiplying by one to cast the string into a number. parseInt would also do the same thing.
Notice that clicks is defined with let. This means that the variable can be changed. var still works of course, but in modern practices its best to use const and let when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button element and listen for the click event. First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string.
Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.
The issue here is that there is no initial value for the fontSize of your <p> tag so div.style.fontSize returns an empty string.
You can use window.getComputedStyle instead of div.style.fontSize and you will get the current fontSize.
There is already a post explaining this method
https://stackoverflow.com/a/15195345/7190518
You don't have an initial font-size style on your <p> tag, so it div.style.fontSize is always empty. Also, best practice is to always use var when introducing new variables in javascript.
One good trick to help debugging things like these is to use console.log() at various points, and see whats coming out in your browser console. I used console.log(div.style.fontSize) and the answer became clear.
Working below after adding <p style='font-size:12px'>a</p>:
<html>
<button style='font-size:12px;' onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test' style='font-size:12px;'>a</p>
<script>
var clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
var btn = document.getElementById("count");
var newSize = parseInt(div.style.fontSize.replace("pt", "")) + parseInt(clicks);
div.style.fontSize = newSize + "pt";
btn.style.fontSize = newSize + "pt";
}
</script>
</html>
I don't understand the logic of this solution, but you can simplify it avoiding to use a lot of var (anyway always prefer let or const if you don't need to change), using a single function and writing less code.
function increment(e){
const ctrl = document.getElementById('test');
let current = parseInt(e.dataset.size);
current += 1;
e.innerHTML = current;
e.dataset.size = current;
ctrl.style.fontSize = current + 'pt';
}
<button onclick="increment(this);" data-size="20">20</button>
<p id='test' style="font-size:20pt;">A</p>

modular JavaScript to call modal window

I'm using a plugin in pure JavaScript.
Here's a syntax for creating one modal window.
var modalContent = new tingle.modal();
var btn = document.querySelector('.trigger-button-1');
var modalWindow = document.querySelector('.project1-modal');
btn.addEventListener('click', function () {
modalContent.open();
});
modalContent.setContent(modalWindow.innerHTML);
In all, I need to create 8 modal windows, it was achieved with the following code I've written myself:
myModalContent = new tingle.modal();
var myBtn = document.querySelectorAll('button.project__btn');
for (var i = 0; i < myBtn.length; i++){
myBtn[i].addEventListener("click", function(){
myModalContent.open();
// check if a btn has an attribute
if (this.hasAttribute('data-btn')) {
myModalContent.setContent(document.querySelector('.project' + this.getAttribute("data-btn") + '-modal').innerHTML);
// otherwise set it to display only the project 1 modal window
} else {
myModalContent.setContent(document.querySelector('.project1-modal').innerHTML);
}
});
}
HTML (for 8 list elements in all)
<li class="project">
...
<button type="button" class="project__btn" data-btn="1">More</button>
<div class="project4-modal">
...
</div>
</li>
The problem above is solved but since I'm not a very experienced in JavaScript, I'm looking forward to getting a feedback or even a suggestion on how to improve my code.

Categories

Resources