Ensure JavaScript/jQuery function always runs on page load - javascript

I tried all of the alternative examples I could find and couldn't get this to work. I may have it implemented incorrectly. Any help is greatly appreciated.
My issue:
I have a function that is meant to slideDown an alert if specific values in the are in the textarea.
This function works if the user types in the textarea, but the values are usually passed in from another page. How can I make it run without requiring that they interact with the text area?
Here's my example on JSFiddle: Example
And here is the HTML/JS code for easy reading:
HTML
<!doctype html>
<html>
<head>
<title>Alert Test</title>
</head>
<body>
<div class="controls">
<textarea name="q" class="span12" id="textarea" rows="5">one:</textarea>
</div>
Test alert:
<div class="alert alert-error" id="alert" name="alert" style="display: none;">
This is a test alert.
×
</div>
</body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="textAreaReader.js"></script>
</html>
JS:
$(document).ready(function(){
$('#textarea').on('change keyup paste', function() {
var lines = $('#textarea').val();
var fields = ["one", "two", "three"];
var leng;
for (var i=0; i < fields.length; i++) {
if (lines.indexOf(fields[i] + ':') !== -1){
leng = 1;
}
}
if (leng == 1){
$("#alert").slideDown("fast"); //Slide Down Effect
}else{
$("#alert").slideUp("fast"); //Slide Up Effect
}
});
});

Assigning the function to a variable lets you pass it to the textarea handler and run it on page load.
$(document).ready(function () {
var slide = function () {
…
};
$('#textarea').on('change keyup paste', slide);
setTimeout(slide, 500);
});
Sample.

Related

addEventListener() with "click" can't run but no error show up to shuffle text with Chaffle.js

I'm having trouble with Chaffle.js library
I tried with jQuery and pure Javascript to add 1 more event is click to shuffle text when I click on a button with id="test" but they can't work and I don't see any errors show up in F12.
I hope you guys can help me.
Here is my code on Plunker
http://plnkr.co/edit/Yc8OrVW6QgVt0V6t
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chaffle#2.1.0/src/chaffle.min.js"></script>
</head>
<body>
<button id="test">Shuffle</button>
<h1 class="shuffle">This created for shuffle effect but it isn't work</h1>
<h3 data-chaffle="en">About Me</h3>
<script>
var elements = document.querySelectorAll("[data-chaffle]");
Array.prototype.forEach.call(elements, function (el) {
var chaffle = new Chaffle(el);
el.addEventListener("mouseover", function () {
chaffle.init();
});
});
document.querySelectorAll("#test").addEventListener("click", function () {
var elm = document.querySelectorAll(".shuffle");
Array.prototype.forEach.call(elm, function (el) {
el.dataset.chaffle ='en';
var chaffle = new Chaffle(el);
el.addEventListener("click", function () {
chaffle.init();
});
});
});
</script>
</body>
</html>
Thank you!!
there is maybe a bug in chaffle.js line 54
if (dataLang.length !== 0) data.lang = dataLang
its not check dataLang for null, so it required to adddata-chaffle attribute to the element
var elm = document.querySelectorAll(".shuffle");
Array.prototype.forEach.call(elm, function (el) {
el.dataset.chaffle ='en'; // <== append this

Show or hide a div depending on a radiobutton (checked/not)

After a long time here and using all your information and comments, I was able to solve all of my code problems. Actually, I don't speak too much English. Sorry for that. Anyway, here we go!
I'm doing business practices and they gave me a project and I've almost finished it, but I cannot deal with it:
I have to detect the OS user system by JS and then after that, if the client is using Windows, I should advise him that he can install a ".exe" to run this app via desktop displaying just a div within a description (here is the div — just a rectangle in this case, so, it doesn't matter). After trying for all of this afternoon, I couldn't solve it and I decided to still testing in at home:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>radio button test [FAILED haha]</title>
<link rel="stylesheet" href="index.css">
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
document.getElementById("good").checked = true;
}else{document.getElementById("bad").checked = true;}
});
if($(#good).is(":checked")){
$(#ident).style.display = "block";
};
</script>
</head>
<body>
<center>
<div id="ident"></div>
<form action="">
<input type="radio" name="system" id="good" value="good">Windows<br>
<input type="radio" name="system" id="bad" value="bad">others
</form>
</center>
</body>
</html>
The problem: I tried to use jQuery to use the Change event on input#windows. The problem is, if it's the default option, the div won't appear, and, if i try it inside out.
I'm done T.T
In advance, thanks.
PS: it's my first post, so if I did something wrong, sorry!
Your problem is that you are not listening to the changeevent. You will have to do that, and when the change event is fired, decide what to do based on the checked/unchecked status of the radio buttons. Also, since you mention that listening to change event doesn't do anything to the radio buttons on page load, that is because you are not evaluating the checked/unchecked status on page load.
p/s: And you forgot to wrap your selector in quotes.
Therefore, the solution is to fire a function on both page load (or DOM ready) and upon change:
$(document).ready(function() {
var systemName = navigator.platform;
if (systemName.indexOf('Win') != -1) {
$('#good').prop('checked', true);
} else {
$('#bad').prop('checked', true);
}
var updateIdent = function() {
if ($('#good').is(":checked")) {
$('#ident').show();
} else {
$('#ident').hide();
}
}
// Update when change event is fired
$('form input[type="radio"]').on('change', updateIdent);
// Update upon DOM ready
updateIdent();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ident">IDENT</div>
<form action="">
<input type="radio" name="system" id="good" value="good">Windows
<br>
<input type="radio" name="system" id="bad" value="bad">others
</form>
Your markup is fine, you're just missing some quotes in your jquery and having problems setting the display: block; This JS will fix it:
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
document.getElementById("good").checked = true;
}else{
$document.getElementById("bad").checked = true;
}
});
if($('#good').is(":checked")){
$('#ident').css('display','block');
};
However, unless you specifically need the radio buttons, you can do without them entirely. Some JS like this will work best:
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
$('#ident').css('display','block');
}else{
$('#ident').css('display','none');
}
});
Hope that helps!
Try this:
$('.radioBtn').change(function () {
if (this.value == 'good') {
$('#ident').show();
} else if (this.value == 'bad') {
$('#ident').hide();
}
});
systemName = navigator.platform;
if (systemName.indexOf('Win') > -1) {
$('#good').prop("checked", true).change();
} else {
$("#bad").prop("checked", true).change();
}
See it in action: https://jsfiddle.net/fmotankv/24/
Also, note that my Fiddle uses CSS to automatically hide the #ident div. I would recommend this method to avoid non-Windows users from potentially seeing the div flash on their screen before being removed by the code.

Focus doesn't work on textarea triggered by javascript onclick event

I have a simple transition thing, where a message says something like "Click here to type" and this is a div which when clicked, hides this div and shows the textarea with a flashing cursor. I have the focus through onload when the page initially loads but I'm after, triggering the focus when wanted.
So I have something like this:
interface
<div id="message" onclick="showPad();"><span class="message">Click to write</span></div>
<form name="entry">
<textarea id="writingpad" name="writingpad" placeholder="write here"></textarea>
</form>
javascript
<script>
function showPad() {
document.getElementById('message').style.display = "none";
document.getElementById('writingpad').style.display = "inline-block";
// this is what I've tried for focus
document.entry.writingpad.focus(); // didn't work
$('#writingpad').live('focus', function() {
// document.entry.input.focus(); possibly redundant
}
$('#writingpad').focus(); // doesn't work
}
</script>
working script
function showPad() {
$('#writingpad').focus();
}
The focusing in your script works, the issue is with the loading.
Instead of using onLoad and live event delegations, you could make sure the script is placed in <head> or <body>.
Also don't need jQuery for this - pure JS:
var message = document.getElementById('message');
var textarea = document.getElementById("writingpad");
function showPad() {
message.style.display = "none";
textarea.style.display = "inline-block";
textarea.focus();
}
Demo
This should work for you.
$(document).ready(function() {
$('#message').click(function() {
$(this).hide();
$('#writingpad').css('display', 'inline-block').focus();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"><span class="message">Click to write</span></div>
<form name="entry">
<textarea id="writingpad" name="writingpad" placeholder="write here"></textarea>
</form>
EDIT
The reason why your version is not working is because you have function that you forget to close it.
$('#writingpad').live('focus', function() {
// document.entry.input.focus(); possibly redundant
}
Should be:
$('#writingpad').live('focus', function() {
// document.entry.input.focus(); possibly redundant
});
Check this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function showPad() {
document.getElementById('message').style.display = "none";
document.getElementById('writingpad').style.display = "inline-block";
// this is what I've tried for focus
document.entry.writingpad.focus(); // didn't work
$('#writingpad').live('focus', function() {
// document.entry.input.focus(); possibly redundant
});
$('#writingpad').focus(); // doesn't work
}
</script>
<div id="message" onclick="showPad();">
<span class="message">Click to write</span>
</div>
<form name="entry">
<textarea id="writingpad" name="writingpad" placeholder="write here"></textarea>
</form>

Simple&Basic JS - 1st attempt to javascript (want it jQuery free)

First attempt to javascript.. not sure what I'm doing wrong...
Trying to clear the "Sample Here" when i hover mouse or focus, or click.
And Alert when the button is clicked..
I'd rather advices how I can avoid using functions inside the HTML and use them
under the to separate js/html completely!
<!DOCTYPE html>
<html>
<head>
<title>Java Script Practicing</title>
</style>
<script>
document.onreadystatechange = function ()
{
if (document.readyState == "complete")
{
//Page Loaded
function go()
{
alert("done");
}
function clear()
{
var x = document.getElementById("x").value;
x = "";
}
}
}
</script>
</head>
<body>
<form method="post">
<input onclick="clear();" type="text" id="x" value="Sample here" />
<button onclick="go();">Click !</button>
</form>
</body>
</html>
HTML5 documents don't require you state type for a <script> element if it's javascript, and you want to state which character set your document is going to use. This is pretty much always going to be utf8.
That said, you want to tap into the DOMContentLoaded event:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Java Script Practicing</title>
</head>
<body>
<form method="post">
<input class="userinput" type="text" value="Sample here" />
<button class="gobutton">Click !</button>
</form>
<script>
document.addEventListener("DOMContentLoaded", function() {
var button = document.querySelector("button.gobutton");
button.addEventListener("click", function(evt) {
console.log("button was clicked");
}):
var input = document.querySelector("input.userinput");
input.addEventListener("click", function(evt) {
input.value = "";
}):
});
</script>
</body>
</html>
If you want to call your functions from the html as you are doing, you need them to be in the global scope.
Take the definitions for the functions go() and clear() out of the onreadystatechange function. You can still use that function to call the other two, but they must be defined globally.
Also, you cannot simply change the value of the variable x and have that update the element with id=x on the page. Instead, you can use ELEMENT.setAttribute('value', '') to clear the value.
function go() {
alert("done");
}
function clear() {
var x = document.getElementById("x");
x.setAttribute('value', '');
}
document.onreadystatechange = function () {
if (document.readyState == "complete") {
go();
clear();
}
}
Mike has answered your question. Just explaining why your way didn't work. Your functions (go, clear) have become local to the onreadystatechange's callback function's scope. I.e a closure

On Same Button-Click, Div fadeOut and fadeIn

i would like to create a one-page website where on click of the button the impressum-div will fade in. Another Click on the same button would then fadeOut the impressum-div.
I already managed it to fadeIn the div on click.
But when I try to use "if" the whole thing doesn't work anymore.
I already found some tipps here and tried them all but nothing really worked for me..
Here my Script-Code:
<script type="text/javascript">
$(document).ready(function() {
function display() {
if (document.getElementById("impressum").style=="none") {
$('#impressum').fadeIn();
}
if (document.getElementById("impressum").style=="block") {
$('#impressum').fadeOut();
}
}
});
</script>
I tried this in several versions (with .click() and so on..), so this is probably totally wrong.
Here my HTML-Code:
<input type="button" id="iButton" value="Impressum" onclick="javascript:display()"/>
<div id="impressum" style="display:none">
<p>Here Impressum</p></div>
Help is very much appreciated, if you could post a complete Function it would bethe best because i am only putting parts wildly together..
Greetings
Just use fadeToggle()
<input type="button" id="iButton" value="Impressum" onclick="javascript:display()" />
<div id="impressum" style="display:none">
<p>Here Impressum</p>
</div>
then
$(document).ready(function () {
$('#iButton').click(function () {
$('#impressum').stop(true).fadeToggle();
})
});
Demo: Fiddle
HTML
<div id="impressum" style="display:none">
<p>Here Impressum</p>
</div>
JavaScript
$('#iButton').click(function () {
$('#impressum').stop(true).fadeToggle();
});
fiddle: http://jsfiddle.net/xKpLe/
You cannot retrieve the display value like that, you need to use window.getComputedStyle:
var elem = document.getElementById("impressum"),
display = window.getComputedStyle(elem,null).getPropertyValue("display");
Fiddle Demo
/* 1: <div onclick="display(this);"></div>*/
var display = function(elm){
var status = G(elm).attrib('data-display')||'false';
if(status=='false'){
G(elm).css({display:'block'});
G(elm).attrib('data-display', 'true');
return false;}
if(status=='true'){
G(elm).css({display:'none'});
G(elm).attrib('data-display', 'false');
return false;}
};
/* 2 */
/* elm.onclick = display;*/
var display = function(ev){
var elm = this||G(ev).source(); //Choice
var status = G(elm).attrib('data-display')||'false';
if(status=='false'){
G(elm).css({display:'block'});
G(elm).attrib('data-display', 'true');
return false;}
if(status=='true'){
G(elm).css({display:'none'});
G(elm).attrib('data-display', 'false');
return false;}
};

Categories

Resources