javascript flush text - javascript

I'm trying to change the text in an h3 tag, but the changes don't happen until that the function is ended. I want to change the text immediately.
For example:
<h3 id="myText"></h3>
<input type="button" onClick="changeText('Hello');">
<script type="text/javascript">
function changeText(str){
document.getElementById('myText').innerHTML = str;
}
</script>
Is it possible to refresh the screen immediately after changing the text?
(Like flush() command in C).
Note that if I put an alert after the command, the text is changed immediately:
function changeText(str){
document.getElementById('myText').innerHTML = str;
alert('HelloWorld');
}

To force an immediate refresh, you can do this :
document.getElementById('myText').innerHTML = str; // change the dom
setTimeout(function(){
// do other things
}, 0);
The do other things code will be executed after the refresh.
But it's highly unusual to have a script go on running for seconds.

If you are talking about the refresh all the page, you will lose the content you have changed on the client side because it is stateless (between requests). If you persist it on a repository (session, application, files you can read and write, databases, etc..) on server side you can read from the server side and keep it on your html elements.
In Javascript you could implement an dictionary (element id on key and innerHTML on value) and use it as a cache and implement a flush method to display all changes, try something like:
<script>
var cacheChanges = {};
function addChange(element, value){
cacheChanges[element] = value;
}
function flush() {
for(var i in cacheChanges)
{
var element = document.getElementById(i);
if (element) {
element.innerHTML = cacheChanges[i];
}
}
}
function ChangeSomething(){
// do some changes
addChange('myText', 'Hello');
addChange('myText2', 'Hello 2');
addChange('myText3', 'Hello 3');
// apply all them
flush();
}
</script>
and in your html:
<h3 id="myText"></h3>
<h3 id="myText2"></h3>
<h3 id="myText3"></h3>
<input type="button" onClick="ChangeSomething();">

Related

Update div only if a certain conditions holds true

I am writing a simple webserver with micropython.
I want to switch on a relay for a certain duration (given in input by the user from the HTML form).
When the relay is off, I display a div with the input form for the duration and the activation button.
When the relay is on, the same div is replaced with a countdown; when the relay is on I want to refresh the div every second so that the countdown is updated. When the relay is off, I don't want the div to update because otherwise, if you try to input the duration, every second the input number in the box is cleared.
My div is updated by the following script:
<script>
$(document).ready(function () {
setInterval(function () {
$("#div_name").load(window.location.href + " #heatingDiv");
}, 1000);
});
</script>
The div is:
<div id="div_name">
<h1>Title</h1>
insert_content
</div>
The keyword "insert_content" is replaced with the HTML code inside the micropython program (accordingly to the relay state) before the HTML response is sent.
With the previous code everything works fine except for the fact that the div is updated every second even when the relay is off, making it impossible to input the duration in the form.
What I'd like to do is passing an argument to the script similarly as when one uses onClick to call it (I can modify "state" within micropython before sending the response):
<div id="div_name(state)">
<h1>Title</h1>
insert_content
</div>
and the script should look like:
<script>
$(document).ready(function () {
setInterval(function (var state) {
if(state){
$("#div_name").load(window.location.href + " #heatingDiv");
}
}, 1000);
});
</script>
Of course this does not work because id=div_name is not a function call: it is just to give an idea of what I'd like to achieve.
How can I do that?
Why not use a data attribute:
const $div = $("#div_name");
const state = $div.data('state');
if (state) {
setInterval(function() {
$div.load(window.location.href + " #heatingDiv");
}, 1000);
}
// if you are wanting to do the interval to check if the state changes, you could change it around
setInterval(function() {
const state = $div.data('state');
if (state) {
$div.load(window.location.href + " #heatingDiv");
}
}, 1000);
<div id="div_name" data-state="state">
<h1>Title</h1>
insert_content
</div>
Perhaps if you are only wanting to run the load when the state changes, you may be better of with a MutationObserver watching the data attribute instead of a timeout

Unable to get script to send and html to receive and show text via 'onclick'

I am just teaching myself coding and am stuck, please go easy on me as I am a newbie...... I would appreciate any help with my website...
I have created this code which works fine.....
<script type="text/javascript">
function swapImage3(id,primary,secondary,thirdly,fourthly,fifthly) {
src=document.getElementById(id).src;
if (src.match(primary)) {
document.getElementById(id).src=secondary;
greeting='Click two';
} else if (src.match(secondary)) {
document.getElementById(id).src=thirdly;
greeting='Click three';
} else if (src.match(thirdly)) {
document.getElementById(id).src=fourthly;
greeting='Click four';
} else if (src.match(fourthly)) {
document.getElementById(id).src=fifthly;
greeting='Click five';
} else if (src.match(fifthly)) {
document.getElementById(id).src=primary;
greeting='Click one';
}
}
</script>
<body>
<div id="carousel_containerSL">
<div class="text14">
<div id="slider3">
<div class="wrap">
<img id="three"
draggable="false"
src="images/COL1.jpg"
onclick="swapImage3('three', 'images/COL2.jpg', 'images/COL3.jpg',
'images/COL4.jpg', 'images/COL5.jpg',
'images/COL1.jpg')"
onmouseout="this.src='images/COL1.jpg'"
onclick="swapImage3(
<h3 class="captz">
<script>
document.write ("greeting")
</script>
</h3>
Except...
...although my pictures rotate fine using 'onclick' and revert to the original onmousout, I have a total brain-fog regarding getting the text in the:
document.write ("greeting")
position at the bottom underneath each picture to rotate with the same onclicks... I am attempting to get it to read from variable:
greeting="Click"
in the top script... but I fear the is my mistake??...
So to clarify, I wish to change some text and get it to rotate with the pictures... I am running before I can walk, but everything else seems to work on my site except this...
Any help??? Please??
Don't use document.write()...ever. It is a very old way of adding content to a document while the document is being built. Using it after the document is built, which is what you are trying to do, will cause the existing document to be thrown away and an entirely new one to be written. Instead use innerHTML or textContent to inject the content into the document (a.k.a. the "DOM").
Here's an example of how to structure the code with your click event working. I'm not sure what you were after with your mouseout function since it simply sets the image source to the same value that it already had.
// When the document is loaded run the function called "init"
window.addEventListener("DOMContentLoaded", init);
function init(){
// This function will run as soon as the document is loaded and ready for interaction
// Set up variables that will need to be used throughout the function
// These variables will point to the HTML objects you need to interact with
var img = document.getElementById("three");
var h3 = document.querySelector("h3.captz");
// Set up event handling functions:
img.addEventListener("click", function(e){
swapImage3(e.target, 'https://cdn0.iconfinder.com/data/icons/social-flat-rounded-rects/512/facebook-256.png', 'https://cdn0.iconfinder.com/data/icons/social-flat-rounded-rects/512/facebook-256.png',
'http://blueblots.com/wp-content/uploads/2010/09/high-details-social-facebook-icon.jpg', 'http://wfarm4.dataknet.com/static/resources/icons/set113/badaf4a8.png', 'http://www.seaicons.com/wp-content/uploads/2016/03/Facebook-icon-26.png');
});
img.addEventListener("mouseout", function(e){
e.target.src='http://www.seaicons.com/wp-content/uploads/2016/03/Facebook-icon-26.png'
});
function swapImage3(obj,primary,secondary,thirdly,fourthly,fifthly) {
console.log(obj.src,primary,secondary,thirdly,fourthly,fifthly)
var greeting = "";
switch(obj.src){
case primary:
greeting = 'two';
break;
case secondary:
greeting = 'three';
break;
case thirdly:
greeting = 'four';
break;
case fourthly:
greeting = 'five';
break;
case fifthly:
greeting = 'one';
break;
}
h3.textContent = "Click " + greeting;
}
}
img {width:10%;}
<div id="carousel_containerSL">
<div class="text14">
<div id="slider3">
<div class="wrap">
<h3 class="captz"></h3>
<img id="three" draggable="false" src="http://www.seaicons.com/wp-content/uploads/2016/03/Facebook-icon-26.png">

Do I need to create multiple functions for multiple actions or can they all be housed in the same function?

I'm working on a script to simulate a page change in a Questionnaire I'm building. I figured maybe I could use a bunch of "if" statements to house all the logic but it's not working right, before I go and create separate functions I'd like to know if it's possible to put them all in one single function.
So far this is the script
function pageChange(){
var chng1 = document.getElementById("p1next");
var chng2a = document.getElementById("p2back");
var chng2b = document.getElementById("p2next");
var chng3a = document.getElementById("p3back");
var chng3b = document.getElementById("p3next");
var pg1 = document.getElementById("page01");
var pg2 = document.getElementById("page02");
var pg3 = document.getElementById("page03");
if (chng1.click){
pg1.style.display="none";
pg2.style.display="block";
}
if (chng2a.click){
pg1.style.display="block";
pg2.style.display="none";
}
the "p1next, p2back, p2next etc." are IDs I gave the buttons on the pages, which I have in DIVs that I respectively named "page01, page02, page03 etc."
Without the 2nd if statement the script works exactly how I want it, it changes the display for "page01" to none and the div for "page02" to block. When I add the second if statement it doesn't work.
The reason I want to do it like this rather than making actual pages is because I don't want the data to get lost when they load another page. Am I on the right track or do I need to create a new function for each page?
Not exactly on the right track, you should use onclick events, instead of if (x.click) like this:
var chng1 = document.getElementById("p1next");
var pg1 = document.getElementById("page01");
var pg2 = document.getElementById("page02");
// Events
chng1.onclick = function(){
pg1.style.display="none";
pg2.style.display="block";
};
This will save your function until the element is clicked and then execute that function. In your case, it is executed on page load, and at that moment the user is not clicking anything.
Why not try something like this:
HTML:
<div class="page" data-pg="1">...</div>
<div class="page" data-pg="2">...</div>
<div class="page" data-pg="3">...</div>
<input id="btnPrev" type="button" value="Prev" />
<input id="btnNext" type="button" value="Next" />
jQuery:
var pageNum = 1;
$(document).ready(function () {
$("#btnPrev").on("click", function () { ChangePage(-1); });
$("#btnNext").on("click", function () { ChangePage(1); });
ChangePage(0);
});
function ChangePage(p) {
$(".page").hide();
pageNum += p;
$(".page[data-pg='" + p + "']").show();
$("#btnPrev").removeAttr("disabled");
$("#btnNext").removeAttr("disabled");
if (pageNum === 1) $("#btnPrev").attr("disabled", "disabled");
if (pageNum === $(".page").length) $("#btnNext").attr("disabled", "disabled");
}
That way you can easily grow your number of pages without changing the script. My apologies by the way for doing this in jQuery.
Update:
Have a lot of time on my hands today and have not coded for while using vanilla Javascript. Here's the version of the code using plain js: https://jsfiddle.net/hhnbz9p2/

Load html on an element with jQuery

I am trying to fill the html of a component with the result of an AJAX request, and it works... but only first time. This is for a phonegap application, and it tries to "encapsulate" a web on the app. I show you my code and after I´ll explain better.
My code is this:
function loadPage(rute, callback)
{
console.log("ruta: " + rute);
jQuery.get(rute, function(htmlTemplate)
{
var data = eraseExtraContentExternalPages(jQuery(htmlTemplate).filter("#wrapper"));
data = eraseLinksExternalPages(data);
console.log("#############BODY(wrapper)############# " + data.html());
jQuery('body').html(data.html());
});
}
function eraseExtraContentExternalPages(data)
{
data.find('#secondary').remove();
data.find('#dd_ajax_float').remove();
data.find('#author-bio-box').remove();
data.find('.googlepublisherpluginad').each(function(index){jQuery(this).remove();});
return data;
}
function eraseLinksExternalPages(data)
{
data.find("a").each(function(index)
{
var a = jQuery(this);
var href = a.attr("href");
if(href && href.indexOf(".jpg")==-1 && href.indexOf(".gif")==-1 && href.indexOf(".png")==-1 && href.indexOf(".jpge")==-1)
a.attr("href","javascript:loadPage('"+ href +"');");
});
return data;
}
What I do (I think is simple), I am trying to erease many html elements that are annoying on the app, and after change the href attribute of the "a" element, for a javascript action (loadPage), and it seems that works, becouse on the first console.log of the loadPage function I can see (when I press a link) how the rute is the correct, and on the second console.log I can see ALL THE CONTENT of data.html on the logcat (with eclipse), but the screen stay white-gray and with a little square on the left top corner...
Any Idea?? Why the html that I can see on the logs doesn´t load on the body??
Thank you very much!!

How Can I Insert My Javascript Into My Drupal Site/Node

I'm trying to insert a cookie that is provided by a video host that will resume a video where the user left off. They have an example that obviously works. When trying to insert this into my Drupal site, the cookie won't work. The video just starts back at the beginning.
I have enabled "PHP input filter", as I read that I needed to do that for drupal to insert the script. Please see the code that is in my node below.
Can anyone help me figure out why this isn't working, how to get it to work, or a better way of doing this with Drupal?
Thank you,
<script type="text/javascript">
wistiaEmbed.ready( function() {
var all_cookies = document.cookie.split(';'), // gets the value of the cookies on the page
cookie_str = "resume_video=",
resume_cookie = does_resume_cookie_exist(all_cookies);
function does_resume_cookie_exist(cookie_arr) {
var i, curr_string, found;
for (i = 0; i < cookie_arr.length; i++) {
curr_string = cookie_arr[i];
if (curr_string.substring(0,5) === cookie_str.substring(0,5)) {
// we've found it!
found = curr_string;
break;
}
}
return found;
}
function set_cookie_time(t) {
document.cookie = cookie_str + t.toString(); // this takes the time (t) and sets the cookie with that time
}
if (resume_cookie) {
num = resume_cookie.split('=')[1];
start_time = parseInt(num);
wistiaEmbed.time(start_time).play(); // plays the video at the specific time defined in the cookie upon return to the page
} else {
set_cookie_time(0); // places a cookie on the visitor
wistiaEmbed.play(); // starts the video from the beginning
}
wistiaEmbed.bind("timechange", function(t) { // on timechange, reset cookie
set_cookie_time(t);
});
wistiaEmbed.bind("end", function() { // if person has watched the entire video, sets the video to beginning upon retun
set_cookie_time(0);
});
});
</script>
<div id="wistia_npcc5k96s9" class="wistia_embed" style="width:640px;height:508px;"> </div>
<script charset="ISO-8859-1" src="http://fast.wistia.com/assets/external/E-v1.js"> </script>
<script>
wistiaEmbed = Wistia.embed("npcc5k96s9");
</script>**strong text**
What version of drupal are you using? Does the code that you gave actually output in your request response?
There are several solutions to this (IMO).
If the code is showing up in the response, it could be some other javascript error that preventing your code from executing.
If that snippet of code is applicable to all nodes of that type you can use the node_view hook in order to inject your code on that node type, for example (I am assuming D7):
function mymodule_node_view($node, $view_mode)
{
if($node->type =='video_page')
{
drupal_add_js('resume_video.js'); // this js holds your code snippet
}
}
Here's a reference that could help you out
https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7
You can similarly inject that snippet of code at the theme layer using a theme hook, probably hook_preprocess https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess/7
Hope that helps.

Categories

Resources