DYNAMIC HTML (FONT SIZES) - dhtml

I've written a code that displays 2 buttons and one text. When we click on the button, "GROW" the size of the text should grow and when we click, "SHRINK" the size should reduce. But this is working only for one click. When I click second time, the functions are not invoked. Why is this happening?
Here is the code for it..
<html>
<head>
<script type="text/javascript">
function Grow()
{
var a=document.getElementById(1);
a.style.fontSize=a.style.fontSize+50;
}
function Shrink()
{
var a=document.getElementById(1);
a.style.fontSize=20;
}
</script>
</head>
<body>
<input type="button" value="grow" onclick="Grow()">
<input type="button" value="shrink" onclick="Shrink()">
<p id="1"> Hello </p>
</body>

When you perform the grow action for the first time it automatically uses the units px as you started off with a null value. You will need to parse the value of .fontSize before you can perform arithmetic on it. Try this...
parseInt(a.style.fontSize.replace('px', ''));
to get a numerical value you can perform arithmetic on.
In full...
function Grow()
{
var a=document.getElementById(1);
// Get a number we can perform arithmetic on
size = parseInt(a.style.fontSize.replace('px',''));
// Additional check needed because original dimensions not specified
if (!isNaN(size)) { // If we now have a number we can use
a.style.fontSize=size+50;
} else { // Otherwise, set to 50 (assuming we are starting from 0px)
a.style.fontSize=50;
}
}

Related

How to use interval in alpine js?

I am trying to add a timer to my cards. So, what I do is. I receive data from DB and pass the data to the records[] array and then I show the data on frontend.
<template x-for="record in records">
<span x-text="record.created_at">2022-10-31 18:41:20</span>
</template>
But what I want is to show the seconds between created at to now time and the seconds should be changed as time passes kind of like how much time is passed since the record is created.
Actually, in my case, I need to change the text within the loop. I tried something like this
https://cdn.jsdelivr.net/gh/kevinbatdorf/alpine-magic-helpers#latest/dist/interval.js
<template x-for="record in records">
<span x-text="$interval(getTimer(record), 1000)">2022-10-31 18:41:20</span>
</template>
<script type="text/javascript">
function dateComponent() {
return {
init: function() {
// fetch data
},
getTimer: function(record) {
console.log(record)
}
}
}
</script>
But this runs the interval only once. Is this possible in alpine js. and if yes, please guide me to where I am doing wrong.

firefox web extension tutorial: script repeat itself

I've followed the following guide to train myself at firefox addon:
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension
Then I started tweaking the code to add my own functions, keeping the same architecture/logic.
But then I noticed that my functions, when launched by clicking in the menu, execute sereval times, actually the number of times I've clicked in the addon menu since I loaded the page.
example: I created a menu option called Repeat Test that links to a function called "Repeat Test" that is just console.log('1');
- first click, I get 1
- second click, I get 1 / 1
- third click, I get 1 / 1 / 1
where can that come from ?
my code:
beast.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="choose_beast.css"/>
</head>
<body>
<div class="beast">Remove Model Map</div>
<div class="beast">Color Formulas</div>
<div class="beast">Image Overlay</div>
<div class="beast">Repeat Test</div>
<script src="choose_beast.js"></script>
</body>
</html>
choose_beast.js:
function optionSelection(myvar) {
switch (myvar) {
case "Remove Model Map":
return "modelMap";
case "Color Formulas":
return "colorFormulas";
case "Image Overlay":
return "imageOverlay";
case "Repeat Test":
return "repeatTest";
}
}
document.addEventListener("click", function(e) {
if (!e.target.classList.contains("beast")) {
return;
}
var clickedOption = e.target.textContent;
var optionActivated = optionSelection(clickedOption);
chrome.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {option: optionActivated});
});
});
and finally, beastify.js:
function myaddon(request, sender, sendResponse) {
switch (request.option){
case "modelMap": removeModelMap();
case "colorFormulas" : colorFormulas();
case "imageOverlay" : overlay();
case "repeatTest" : repeatTest();
}
}
function repeatTest()
{
console.log('1');
}
chrome.runtime.onMessage.addListener(myaddon);
I've found the issue here. this code
chrome.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
is contained into the click event manager, so every time you click, the script is executed, which adds to the fact that later on a message is sent to the script every time a click is made.
I don't know if this is a mistake or not (it's actually like this on the mozilla website):
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension
but it was quite annoying for me. I'll notify them.

Problems with mouse events on newly created CKEditor instance

I'm trying to create a create a new CKEditor ver4 instance in response to the user clicking on an element. Due to the nature of the application, I can not use the "autoInline" feature as outlined in the CKEditor Sample. While the sample below does in fact create an editor instance, that instance has a significant problem. Inline instances are supposed to disappear when the user clicks away from them. In this example however, the user must first click away, click back into the instance, and then click away again. How can I prevent this?
<!doctype html>
<html>
<head>
<script src="jspath/ckeditor.js"></script>
<script>
var editor = null;
CKEDITOR.disableAutoInline = true;
function init() {
var e2 = document.getElementById("element2");
e2.addEventListener("click", function () {
if(!editor) {
editor = CKEDITOR.inline(e2);
editor.on('instanceReady', function () {
console.log("instanceReady")
console.log(editor.focusManager.hasFocus);
});
editor.on('focus', function() {
console.log("focus");
})
editor.on('blur', function() {
console.log("blur");
editor.destroy();
editor = null;
})
}
})
}
</script>
</head>
<body onload="init()">
<div tabindex="0" id="element2" style="background-color: yellow;" contentEditable = true>Element 2</div>
</body>
</html>
Despite the fact that editor.focusManager.hasFocus was true, the editor's element did not in fact have focus. Perhaps this is a bug? Anyway, adding editor.focus(); to the instanceReady function resolved the issue.

Pop up window self close function; close the site as well

I have an Ajax call back function which call to a PHP function check the file modified time.
I uses timer to execute it every 50 seconds.
<script type="text/javascript">
setInterval("_checkPopUpUpdate()", 50000); //50 seconds
</script>
function _checkPopUpUpdate()
{
var callback=new Object();
callback.success=this.onExternalSuccess;
callback.failure=this.onExternalFailure;
YAHOO.util.Connect.asyncRequest('GET','/ci/ajaxCustom/ajaxCheckPopupUpdate',callback);
};
The PHP function checks whether the file modified time has different between the first load session time
$announcement_Popup_Path = HTMLROOT . $this->data['attrs']['file_path'];
// Call model function
if($this->data['attrs']['file_path'] !== '' && file_exists($announcement_Popup_Path))
{
//When the announcement content load, it always stores the modified time into session
$this->CI->load->model('custom/checkupdate_model');
$firstloadTime = filemtime($announcement_Popup_Path);
$this->CI->checkupdate_model->store_AnnouncementPopupSession($firstloadTime);
//$this->data['Popup'] = file_get_contents($announcement_Popup_Path);
}
function store_AnnouncementPopupSession ($popupTime)
{
$sessionPopupTime =array("annoucementPopUp"=> $popupTime);
$this->session->setSessionData($sessionPopupTime);
}
function announcement_pop()
{
$file_path='/euf/assets/announcements/pop_up_announcement.html';
$announcement_Popup_Path = HTMLROOT . $file_path;
if(file_exists($announcement_Popup_Path)) {
$currentAnnouncementPopUpTime = filemtime($announcement_Popup_Path);
$oldannouncementPopupTime = $this->session->getSessionData("annoucementPopUp");
if($currentAnnouncementPopUpTime !=$oldannouncementPopupTime) {
//comparing the content and update the time, when they are different, send back update content
$this->store_AnnouncementPopupSession($currentAnnouncementPopUpTime);
//echo $currentAnnouncementPopUpTime;
echo $file_path;
}
else {
echo "no update";
}
}
}
When the file modifed time has changed, it will return to ajax call back and grab the HTML content in my web server to Pop up an annoucement pop up window.
function onExternalSuccess (o){
if(o.responseText!==undefined)
{
var str=o.responseText;
if(str !== 'no update') // Then pop up.
{
L=screen.width-200;
T=screen.height;
popup=window.open(str," ",'alwaysRaised=yes,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no,height=150,width=364,left="+L+",top="+T');
//popup=window.open(str,"",'alwaysRaised=yes,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no,height=100,width=330');
for (i=0;i<200;i++)
{
T=T-1;
popup.moveTo(L,T);
}
}
}
};
It works fine for Firefox and Chrome, however IE7 is a bit bugy, sometime the pop up does not come out.
<html>
<head>
<title>Internal alert</title>
<link rel="stylesheet" type="text/css" href="/euf/assets/css/pop_up_ann.css" media="screen, projection" />
<script type="text/javascript">
var howLong = 50000; //5 minutes, 1 seconds = 1000 milliseconds.
t = null;
function closeMe(){
t = setTimeout("self.close()",howLong);
}
</script>
</head>
<body onLoad="closeMe();self.focus();">
<div id="cs_popup">
<div class="popup_rounded-corner-top">
<div id="popup_ann">
<div id="popup_ann_title">IE7 pop-up EMEA test close </div>
<div id="popup_ann_from"> PLC team - 05/01/2011 at 12:10</div>
<div id="popup_ann_content">
Something has changed in the<em>"Alerts"</em> section of S4S since your last visit.
Make sure you go there as soon as you can to be informed about the current situation.
</div>
</div>
</div>
<div class="popup_rounded-corner-bottom"></div>
</div>
</body>
</html>
The main problem i have here it is self-close function. It close my pop up window and the website as well. Any hints? Also, i am not sure whether my whole pop up annoucement logical structure is correct, is there anyway? thanks
Opening a popup window for an announcement like this could be problematic for people running popup blockers, which typically only allow popups to appear in response to a user-initiated event like clicking on something. A better approach would be to use an inline popup which would also give you the opportunity to display the popup modally (i.e. mask the rest of the page with a semi-transparent div) if you require them to acknowledge your message.
The use of self.close() should not close the original window/tab opened by the user, it should only close things that have been 'open'ed so I'm not sure what's going on there, I suspect you haven't told us everything :) An alternate approach might be to modify your popup function to close the window rather than have the window close itself.
// open popup ... then set timeout to close it
var popupDelay = 50000;
setTimeout(function() {
popup.close();
}, popupDelay);
This may work a little better, not sure. But in the long run, I highly recommend avoiding popups and using something inline instead.

Partial page refresh for evary X seconds with Jquery and Ajax?

1) I have to change images dynamically according to values for every x seconds.
I'm using the following function:
setInterval(function() {
$("#content").load(location.href+" #content>*","");
}, 5000);
It works fine for updating the value, but the images not getting updated into its position.
2) From the 1st question i want to know whether the jquery and css files included in the head tag will load every x seconds or not. if not how to load?
Please give me the suggestion.
If you are returning a whole HTML page and returning it into the body of another page, that is a bad idea.
Think about it, your html structure would be something like
<doc type>
<html>
<head>
</head>
<body>
<div>
<doc type>
<html>
<head>
</head>
<body>
<div>
</div>
</body>
</html>
</div>
</body>
</html>
Ideally you should be retuning just the content that is to be displayed, not everything.
If you are just updating images, there usually is no need to make an XHR call. You can just set the image src and force the browser to update that content that way.
Does this need to be done with Ajax at all? How many images are you going to cycle through? If it is only a few, just keep all of the src's on the page and switch the image src attribute periodically. This requires no page reload. You may also want to preload all the images so there is no flicker when changing to the other image. For example:
$(function () {
var images = ['1.png', '2.png', '3.png'];
$.each(images, function (index, src) {
$("<img />").attr('src', src); //preload
});
var keep = 1;
setInterval(function () {
$("#main_img").attr('src', images[keep]);
keep++;
if (keep >= images.length) { keep = 0; }
}, 5000);
});
Now if you don't want to hard code the image urls in the JS, you can load them initially with a single Ajax request.
I would only recommend using Ajax to do all the work if you are talking about an unpredictable set of images or some massive number of images.

Resources