Replacing an element on page using JavaScript - javascript

I have a video player that runs client-side, and I want to store a configuration for it so I don't have to write it each single time.
I had an idea where I could place a marker in the markup, such as:
<player id="Player1" #marker></player>
Or something to that effect, and then replace #marker with the settings I have stored in the javascript function.
I know some basic Javascript, but I have never done something so advanced.
Here is an example:
<script type="text/javascript" language="JavaScript">
flowplayer("player", "http://www.easymuaythai.com/Videos/FlowPlayer/flowplayer-3.2.7.swf", #marker);
</script>
Where it says #marker, I want to replace it with:
{
clip: {
Scaling: 'fit',
onStart: function (clip) {
var w = parseInt(clip.metaData.width, 10),
h = parseInt(clip.metaData.height, 10);
$(this.getParent()).css({
width: w,
height: h
});
}
}
}

You can use JQuery,
add this to the Head section of your page :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
then write this in your js file or section
$('#player1').attr('playerConfiguration', 'Value');
that will cause <player id="Player1" playerConfiguration="value"></player>
hope that helps...

Maybe this will help you ? It creates and sets an attribute (marker) to the player node and it gives it a value (config)
<html>
<head>
<script type="text/javascript">
var p = {
onload: function() {
var markerAttribute = document.createAttribute("marker");
document.getElementById("Player1").setAttributeNode(markerAttribute);
markerAttribute.nodeValue = "config";
}
};
</script>
</head>
<body onload="p.onload()">
<div>
<player id="Player1"></player>
</div>
</body>
</html>

You could include Jquery and do the following:
$("#Player1").attr('config', 'write=all&settings;you,need');
Or something like:
$("#Player1").replaceWith('The html code u want');

Related

Is there any way for more than one Google Translate widget to be loaded on a page

Is there any way possible to load a Google Translate widget in the sidebar and one in the footer, for example.
Every way I've tried has only loaded so that both appear in the location of the first instance on the page.
After a bit of tinkering I kinda felt obligated to solve the puzzle! You can skip to the good part by checking out the jsfiddle: (it works as of now but knowing google it might not tomorrow)
http://jsfiddle.net/melfy/15zr6ov0/
Lets begin:
First google translate is loaded and adds a listener for a select box it adds to the DOM after you call the right element but we need that change event to call a change for a select box we're going to clone from the original one to get google to update the translation, this gets a bit messy as we over take the prototype (which is usually bad practice)
Start by adding your header element:
<div id="google_translate_element"></div>
Then we add our footer element:
<div id="google_translate_element2"></div>
Next we pull in the google translator
<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
Now we get to the good part:
<script type="text/javascript">
// store google translate's change event
trackChange = null;
pageDelayed = 3000;
// overwrite prototype to snoop, reset after we find it (keep this right before translate init)
Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(a,b,c) {
reset = false;
// filter out first change event
if (a == 'change'){
trackChange = b;
reset = true;
}
if(c==undefined)
c=false;
this._addEventListener(a,b,c);
if(!this.eventListenerList)
this.eventListenerList = {};
if(!this.eventListenerList[a])
this.eventListenerList[a] = [];
this.eventListenerList[a].push({listener:b,useCapture:c});
if (reset){
Element.prototype.addEventListener = Element.prototype._addEventListener;
}
};
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element');
let first = $('#google_translate_element');
let second = $('#google_translate_element2');
let nowChanging = false;
// we need to let it load, since it'll be in footer a small delay shouldn't be a problem
setTimeout(function(){
select = first.find('select');
// lets clone the translate select
second.html(first.clone());
second.find('select').val(select.val());
// add our own event change
first.find('select').on('change', function(event){
if (nowChanging == false){
second.find('select').val($(this).val());
}
return true;
});
second.find('select').on('change', function(event){
if (nowChanging){
return;
}
nowChanging = true;
first.find('select').val($(this).val());
trackChange();
// give this some timeout incase changing events try to hit each other
setTimeout(function(){
nowChanging = false;
}, 1000);
});
}, pageDelayed);
}
</script>
You can change the pageDelayed variable to trigger quicker or slower but if it's in your footer, bumping it up to delay longer may help it work more efficiently depending on your page load
Unfortunately, you can not have the widget be loaded more than once in a single page. Google just doesn't allow for that. One potential workaround would be putting the code in an iFrame and then putting two iFrames onto your webpage.
Create a file called iframe.html
<html>
<head>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit">
</head>
<body>
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit(){
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
</body>
</head>
</html>
In your other file put code something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Google Translate</title>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?b=googleTranslateElementInit"></script>
</head>
<body>
<div id="header" style="background-color: red;">
<iframe src="iframe.html"></iframe>
<strong>A</strong>
</div>
<div id="footer" style="background-color: blue;">
<iframe src="iframe.html"></iframe>
<strong>B</strong>
</div>
</body>
</html>

Changing a javascript variable inside a DIV using JQuery

Firstly - i'm not even sure if the syntax is correct, but what i'm trying to do is, i have a div showing an animated image sequence which picks a position using a variable.
I will eventually use JSON to feed the value being changed, but for now i'm just trying to understand how to use JQuery to change the variable. Here's the code:
<div id="noiseAnimDiv" style="float: center; background-color: #ffffff; ">
<script type="text/javascript" src="./animatedpng.js">
</script>
<script type="text/javascript">
var stoptheClock = 3;
noiseAnim = new AnimatedPNG('noise', './noise/noise0.png', 8, 50);
noiseAnim.draw(false);
noiseAnim.setFrameDelay(stoptheClock, 1000); //spin yet stay on value 3
</script>
</div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(
function() {
$("#stoptheClock").val(6); //
}
);
</script>
Any help much appreciated
code is live btw at so you can at least see the animation seq
http://ashleyjamesbrown.com/fgbp/noise.htm
The AnimatedPNG library you are using only checks the variable's value once - when initialized. in your code, you are changing the value after initializing it.
$(document).ready(
function() {
$("#stoptheClock").val(6); //
}
);
Should be
function() {
stoptheClock = 6;
noiseAnim.draw(false);
noiseAnim.setFrameDelay(stoptheClock,1000);
}
You are not using JQuery for any useful cause in your code, therefore I have removed all of the Jquery parts.

How can show pop when user typing using javascript?

I want to create a function for showing pop or status when user typing something in field, I want to do it without submitting form, I have try following function but its not working properly can anyone let me know where the problem..........?
Javascript
<script type="text/javascript">
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
function checkFile(e) {
if ($('#confirm').val().length > 0) {
alert("txt");
}
}
</script>
HTML
<input type="text" name="text" id="confirm">
Just listen to the onkeyup and onkeydown events. I included a jsfiddle that might help.
jsfiddle
Edit - The Latest Update
Okay, I see you've got your fiddle from Vivek, but you might be interested in this as well. Now I get completely what you want to achieve, and here's a short description. The best practice is to split JavaScript from HTML and avoid putting JavaScript inside HTML head and body as much as you can.
So, first create three files: Test.js Example.html and Test.css. Of course, you also need jQuery file which you just include here inside the head. In Example.html put the following code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="Test.css"/>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript" src="Test.js"></script>
</head>
<body>
<input type="text" id="test"/><span id="popup"></span>
</body>
</html>
In Test.css add some style to your pop-up span element (you could also use division element and style it to your liking if you want fixed height and width, add shadows and so on):
#popup {
background-color: red;
color: white;
display: none;
}
And finally, put the following JavaScript code in Test.js:
$(document).ready( function() {
$("#test").keyup( function() {
if($("#test").val().length>5) {
$("#popup").fadeIn();
$("#popup").html("Invalid length. Maximum is 5.");
}
else {
$("#popup").fadeOut();
}
});
});
By dividing JavaScript, CSS and HTML into separate files, you get much tidier HTML and separated styling and client-side logic from markup.
Old Answer
Wrap the code inside $(document).ready().
Like this:
$(document).ready(function() {
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
});
function checkFile(e) {
if ($('#confirm').val().length > 0) {
alert("txt");
}
}
Also, addEventListener is not available in IE8 and below. You could use the onchange event, like this:
$(document).ready(function() {
document.getElementById("confirm").onchange = checkFile;
});
There is a similar method for IE8 and earlier called attachEvent. In case of using the attachEvent method, it would look something like the following:
$(document).ready(function() {
document.getElementById('confirm').attachEvent('change', checkFile);
approveletter.attachEvent('change', checkFile);
});
You could also use the jQuery.change() as suggested in the comments by Protron:
$(document).ready(function() {
$("#confirm").change(function() {
if ($('#confirm').val().length > 0) {
alert("txt");
}
});
});
And of course it's possible to do it without the classic alert pop-up window. You could create your own HTML division element with display:none and show it when necessary. Just send me a note in the comments if you need instructions on that as well.
Using this, you need not click the web page.
<input type="text" name="text" id="confirm"><br /><br />
<span id="status" ></span>
<script type="text/javascript">
$('#confirm').keyup(function () {
if ($('#confirm').val().length > 0) {
$('#status').html("Text entered");
}
else
{
$('#status').html("Text removed");
}
}
)
</script>

Showing images conditionally

I've been working on a simple website for a while now. The basic coding and CSS are complete, so I am now looking to expand by adding certain features to the website. As it is a fully functioning website that serves a purpose, the main source of revenue comes from Google AdSense. I am looking for a way to show an image if Adblock is detected and another one if if it not.
The method I've found for detecting whether AdSense is active is shown below:
JS (saved as advertisement.js)
document.write('<div id="TestAdBlock" style="display:none;">an advertisement</div>');
The HTML bit:
<div id="adblockFrame">
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
if (document.getElementById("TestAdBlock") != undefined)
{
document.write('<strong>ADBlock Plus</strong> NOT detected!');
}
else
{
document.write('<strong>ADBlock Plus</strong> detected!');
}
</script>
</div>
CSS:
#adblockFrame {
visibility: hidden;
}
What I'm asking is that if someone could be kind enough to show me how, instead of displaying text, the JS would show an image in its place. I'm not that good with JS so I'm grateful for any help.
I would create an empty target div :
<div id="adblockDetector"></div>
<script type="text/javascript">
if (document.getElementById("TestAdBlock") != undefined)
{
document.getElementById('adblockDetector').innerHTML="<img src='noadblock.jpg' alt='no adblock' />";
}
else
{
document.getElementById('adblockDetector').innerHTML="<img src='adblock.jpg' alt='Adblock detected!' />";
}
</script>
Assuming you are using jquery, just because you tagged it:
html
<div id="wheretoappend"></div>
js
var whereToAppend = '#wheretoappend';
var myDiv = $('<div/>', {id: 'mydiv'});
($('#adblockFrame').length)
? myDiv.addClass('hasit').appendTo(whereToAppend)
: myDiv.addClass('doesnt').appendTo(whereToAppend);
CSS
.hasit {background: url('hasit.png');}
.doesnt {background: url('doesnt.png');}
Please, don't use the devil document.write!
If you want to add content to your page, use DOM methods or .innerHTML.
If you want to detect AdBlock, just create a global variable in advertisement.js
For example:
advertisement.js:
window.TestAdBlock = true;
Your page:
<div id="adblockFrame">
<img id="TestAdBlock" alt="AdBlock Detected???" />
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
(function() {
var AdBlockImg = document.getElementById('TestAdBlock');
if (window.TestAdBlock)
{
AdBlockImg.src = "/images/AdBlockDetected.jpg";
AdBlockImg.alt = "AdBlock Detected!";
}
else
{
AdBlockImg.src = "/images/AdBlockNOTDetected.jpg";
AdBlockImg.alt = "AdBlock NOT Detected!";
}
AdBlockImg.title = AdBlockImg.alt;
});
</script>
</div>
Firstly, you shouldn't use document.write for anything. It's just bad practice. But here's generally how I'd do it with jquery, since you tagged it:
<div id="adblockFrame>
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
var adsAllowed = adsAllowed || false;
var src = adsAllowed ? '/images/myAd.png' : '/images/noAd.png';
$('#ad').attr('src',src);
</script>
<img id="ad"/>
</div>
advertisement.js
var adsAllowed = true;

Display MathJax dynamically only when there are delimiters

I have been tweaking with below sample code. The documentation for MathJax isn't very complete. Could someone more experience tell how I should modify the below code so that Tex is only parse when I have specified delimiters like $\alpha$. I would like to make it work like on math.stackexchange.
<html>
<head>
<title>MathJax Dynamic Math Test Page</title>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [["$","$"],["\\(","\\)"]]
}
});
</script>
<script type="text/javascript"
src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full">
</script>
</head>
<body>
<script>
//
// Use a closure to hide the local variables from the
// global namespace
//
(function () {
var QUEUE = MathJax.Hub.queue; // shorthand for the queue
var math = null; // the element jax for the math output.
//
// Get the element jax when MathJax has produced it.
//
QUEUE.Push(function () {
math = MathJax.Hub.getAllJax("MathOutput")[0];
});
//
// The onchange event handler that typesets the
// math entered by the user
//
window.UpdateMath = function (TeX) {
QUEUE.Push(["Text",math,"\\displaystyle{"+TeX+"}"]);
}
})();
</script>
<textarea id="MathInput" size="50" onkeyup="UpdateMath(this.value)"></textarea>
<div id="MathOutput">
You typed: ${}$
</div>
</body>
</html>
The sample code you posted takes the contents of the MathInput and replaces the first MathJax element with the new "math" from the MathInput. What you want is to Typeset the MathInput and create new MathJax elements for the delimited text. I setup a jsFiddle example here:
http://jsfiddle.net/Zky72/2/
The main change is in the UpdateMath function:
window.UpdateMath = function (TeX) {
//set the MathOutput HTML
document.getElementById("MathOutput").innerHTML = TeX;
//reprocess the MathOutput Element
MathJax.Hub.Queue(["Typeset",MathJax.Hub,"MathOutput"]);
}

Categories