javascript replace code within source tag - javascript

Looking for a way to integrate two plugins so that I can have a HTML5 video player with a clickable html playlist. In order to do this, I need to alter one of the plugins so that instead of declaring:
var html = '';
html += '<video width...>'
html += '<source... /source>'
html += '<.video>'
return html
and then refilling on each click, it leaves the current contents alone, only replacing the content of the source tags. I'm trying something like:
html.replace(/'<source>'.*'</source>'/ , '<source> + myNewContent + '</source>');
return html;
I worry that my syntax for .replace() is wrong, or that replace can't handle strings like that.
As a side note, I know I'll need to re-run the function in order for it to reload with the new source, it's just that one plugin is deleting the content of the other, so I don't even have a chance.

Just select it with jquery and overwrite the source. (You could do it without jQ, but nevertheless)
var s = "newSourceString";
$(".videoClass source").html(s);
Now put the classname in your video attributes and fire away.

Just copy paste from the player documentation:
<script>
// JavaScript object for later use
var player = new MediaElementPlayer('#player',/* Options */);
// ... more code ...
player.pause();
player.setSrc('mynewfile.mp4'); /*********** this is what you want ***********/
player.play();
</script>
mediaelementjs.com
EDIT
Answer to the question:
var source = '<source>1 1bla bla bla xx uu dfhf</source>'
var startStr = source.indexOf('<source>') + 8;
var endStr = source.indexOf('</source>');
var oldSrc = source.substring(startStr, endStr);
console.log(oldSrc);
source = source.replace(oldSrc, 'new source');
console.log(source);
I believe this answers your original question.

Many thanks to Rudy for his answer, it put me on the right track, though I changed it to handle a dynamic source (his probably could too).
When you replace youtube videos in mediaelement.js you have to redeploy the plugin, so I ended up emptying the plugin container, storing all the hrefs as a data attribute in the list and then refilling the container with the appropriate html, and recalling the function at the end.
Here's the code:
HTML:
<div class="youtube-slide">
<div id="ytvideo">
<!--here's the initial video source-->
<video width="100%" height="100%" id="player1" preload="none" type="video/youtube" src="http://www.youtube.com/watch?feature=player_embedded&v=JUQXileHPQs" />
</div>
<!--the list of videos, each with a 'data-href' attribute storing a link, and the first one already activated as 'currentvideo'-->
<ul class="vidlist">
<li id="vid1" class="currentvideo" data-href="http://www.youtube.com/watch?feature=player_embedded&v=JUQXileHPQs"> <h3> "Cereus Bright"</h3> unplugged, anthemic ballad<br />recorded live in concert</li>
<li id="vid2" class data-href="http://www.youtube.com/watch?v=0RMtebCrJhY"> <h3> "Winds of Change" </h3>upbeat, funky, with upright bass<br />recorded live in studio </li>
<li id="vid3" class data-href="http://www.youtube.com/watch?v=7Ndm2o6p0A8"> <h3>"Some Strange Hold" </h3> melodic song of heartbreak <br /> recorded live (takeaway style)
</li>
</ul>
</div>
JAVASCRIPT:
<script>
//call function the first time
var player = new MediaElementPlayer('#player1');
$('ul.vidlist li').click(function() {
//clear the div of the player
$('div#ytvideo').empty();
//switch the currentvideo classes, to allow styling
$('.currentvideo').removeClass('currentvideo');
$(this).addClass('currentvideo');
//refill the player div, and call the plugin again
$('div#ytvideo').html('<video width="100%" height="100%" id="player1" preload="none" type="video/youtube" src="' + $(this).attr('data-href') +'"/>');
var player = new MediaElementPlayer('#player1');
});
</script>

Related

Add a link to an image in a Javascrip

hello everybody!
First of all I have to tell you I'm a newbie in terms of HTML, Javascript and coding in general. But I spent last weeks to learn as much as I can.
Now, I run a website and my dev team is not workgin with me anymore, then I have to do all by myself.
My problem is: I have a sort of "big banner" and the image shown is automatically picked up based on your browser resolution (that's fine, I asked for this). Now, what I'm trying to do is to add a hyperlink to this image. I tried many thing, but I couldnt.
Please could you tell me how to edit this code?
Thank you
Miki
<div class="main top">
<div class="main-holder">
<div class="cover-holder big-img-holder" id="img-holder">
<script>
function randomInteger(min, max) {
var rand = min + Math.random() * (max - min)
rand = Math.round(rand);
return rand;
}
var rand = randomInteger(1, {{$lang.extras.number_screenshots_rotations}});
var picture = document.createElement('picture');
var source = document.createElement('source');
source.srcset = '{{$config.statics_url}}/images/bg_rotations/extras-' + rand + 'bd_HD.jpg';
source.setAttribute('media', '(max-width: 2000px)');
var img = document.createElement('img');
img.src = '{{$config.statics_url}}/images/bg_rotations/extras-' + rand + 'bd.jpg';
picture.appendChild(source);
picture.appendChild(img);
document.getElementById('img-holder').appendChild(picture);
</script>
</div>
Usually you can set a hyper link with the HTML tag <a>
So you could try
<a href="your-URL">
<div class="cover-holder big-img-holder" id="img-holder">
<script>
...
</script>
</div>
</a>
Wrap the script in something like
<a id="img-link">
or just change img-holder to be an <a> instead of a <div>
Then somewhere in your script set the url for that <a> container
document.getElementById("img-link").href="url";
There's no href attribute to an image itself, so you must provide it to <a>
That is if you wanna do it dynamically, if the url is always the same, just wrap your <script> block with this
<a href="#">
<img>
</a>
It is easier when you know that DOM is gonna have the same structure, in this case, an image, and an <a> tag wrapping it, just set ids for both, and manipulate their attributes, otherwise, you can also create this <a> element in Javascript, and set the image with .setChild() to it

How to prevent HTML code from running?

I seek to embed multiple iframes on a single page without slowing the page. When I embedded a single iframe, it was running smoothly; added a second and third, and all were slower - despite only one being displayed at a time (using JScript). I presume this is due to the iframe code still executing.
How can I execute code conditionally? In my case, whenever a button is clicked.
Help is appreciated. Fiddle for the exact code I use, with actual content replaced by IDs and iframes by p's: http://jsfiddle.net/aof89Ljt/55/
HTML for the iframes:
<p id="ifr1">
ifr1
</p>
<p id="ifr2" style="display:none;">
ifr2
</p>
<p id="ifr3" style="display:none;">
ifr3
</p>
UPDATE: New JFiddle link with JScript included. End-goal description: I click a button which displays a different embedded Desmos graph, then another graph, then the first graph - in a loop, one at a time (see code). Demonstration gif: https://puu.sh/Bjpil/da9a038e11.gif
UPDATE 2: Solution found; full code: https://jsfiddle.net/32uxrhmw/49/
UPDATE 3: Greatly optimized code: https://jsfiddle.net/32uxrhmw/92/
You need to add the onclick="<your function>" event trigger to the element(s) you want to "do something".
Simple example:
<button onclick="swap()">Button</button>
<iframe style="display: none;" data-url="https://www.example.com" id="iframe">
<p>Your browser does not support iframes.</p>
</iframe>
<script>
function swap() {
e = document.getElementById('iframe'); // get iframe
url = e.dataset.url; // get desired url attribute stored in data-url
e.setAttribute("src", url); // add the iframe src with desire url
e.removeAttribute("style"); // remove styling that hid it otherwise
}
</script>
UPDATED to better apply to question.
UPDATED again to also incorporate #Joe Fitzsimmons good suggestion re handling iframe sources (in his answer).
FINAL ADDITION SEEING YOUR CODE:
Looking at your last code, it seems what you want to do is:
load page with one iframe;
then change iframe displayed when the button is clicked.
If that is what you want, you might want to use this much simpler code:
(Note: I used your code sample as a base, but haven't inserted any src urls - yours may be private, but even if not they all showed the same result so it may confuse other readers)
<style>
.tdropbtn {
background-color: white;
font-size: 16px;
border: none;
cursor: pointer;
color: #0066CC;
}
</style>
<center>
<iframe id="frame" src="https://url1" width="500px" height="400px" frameborder=0></iframe>
</center>
<div style="display:inline;">
<center>
<button onclick="swap()" class="tdropbtn">[+]</button>
</center>
</div>
<script>
var counter = 1;
var firstFrame = "https://url1";
var secondFrame = "https://url2";
var thirdFrame = "https://url3";
var e = document.getElementById("frame");
function swap() {
if (counter == 0){
e.src = firstFrame;
counter++;
}
else if (counter == 1){
e.src = secondFrame;
counter++;
}
else if (counter == 2){
e.src = thirdFrame;
counter = 0;
}
}
</script>
One idea would be to load/remove the source of the iframe onClick.
This is a rough idea of what you could do:
function Swap(id, url) {
document.getElementById(id).src = url;
}
You'd have to show and hide the iFrames as well. Hopefully this could get you on your way. I'm not exactly sure what your end goal is.

Swap images with a list of HTML links with JavaScript

I am trying to swap images using JavaScript. I have a main content area the loads one image. I have a sidebar with a list of links and I want to use JavaScript to change the image with each link. here is my code so far:
<html>
<head>
<title>Rat Dog Inc. ~ Services</title>
<script type="text/javascript">
var myImg;
var myImage= [];
myImage[0] = "../images/rd_surf_large.jpg";
myImage[1] = "../images/laundry.png";
myImage[2] = "../images/tug-o-war.png";
myImage[3] = "../images/cuddlepuppy.png";
myImage[4] = "../images/rd-howling.mp4";
function displayImg(){
document.getElementById('myImage[]');
}
</script>
</head>
<body>
<div id="main">
<img src="../images/rd_surf_large.png" alt="Rat Dog Inc." id="myImg"/>
</div>
<div id="sidebar">
<h2>Rat Dog Inc. Most Popular Services</h2>
<ul>
<li>Surfing Lessons <span style="font-size: 12px">(img)</span></li>
<li>Laundry Folding <span style="font-size: 12px">(img)</span></li>
<li>Tug-O-War Arm Workouts <span style="font-size: 12px">(img)</span></li>
<li>Cuddling <span style="font-size: 12px">(img)</span></li>
<li>Howling Lessons <span style="font-size: 12px">(video)</span></li>
</ul>
</div>
Ok. So here's the deal.
When you put your image on your page , like this:
<img src="image1.jpg" id="myImage">
And we assign the I'd 'myImage' to it....if we want to change the image via a link (I prefare a button), we use javascript in a way to manipulate it.
You simply use this method known as :
document.getElementById()
Which finds an element in our page by its I'd.
So if we put this button on our page:
<button onclick="changeImage()">Change The Image</button>
And put this script (which has the changeImage() function) :
<script>
function changeImage(){
var myImage = document.getElementById("myImage");
//then we change the src of the image
myImage.src="image2.jpg"
}
</script>
Our image will change of we click the button.
For reference , please visit http://www.htmldog.com/guides/javascript/intermediate/thedom
Thank you
You can use document.getElementById("image").src="image.png"; to change the src tag of an element.
Although for what you are doing, I reccomend you take a look at jQuery
please try and use this method of getElementById
For example:
<img id="image" src="image1.jpg">
<button onclick="changeToImage2('image')">Image 2</button>
<script>
function changeToImage(id) {
var myImage = document.getElementById(id);
myImage.src = "image2.jpg";
}
// then create other buttons and other functions to change the image.
</script>
Your javascript is incorrect. I'm not quite sure you understand how it works.
First of all, your function doesn't accept any parameters, and yet you're providing it with one. It will just ignore this because it doesn't know what to do with it.
Next, your document.getElementById in your displayImg() has the wrong input. Right now it's literally looking for an element with the ID "myImage[]"... of which there are none.
Also, you have a variable you never use (myImg). You should probably get rid of it.
Again, I'm getting the sense that you don't really know javascript that well or don't get the theory behind it. If you need help, w3schools has some great tutorials.

Implement site with text reader

I have decided to start a new project.
This project is a spell checker to help children and send the report on how well the child is performing to the teacher.
I have already set up where the teacher can place the word, and what I now need to do is that when the pupil clicks the button, the word gets read out loud.
Is there any plugin that I could use?
I'm not worried about how the pupil will access the word but how to make the word be read out.
Any language will be fine.
Thank you all for your time.
I guess the easiest thing would be to use html5 audio to play the according word from the webserver whenever it is clicked:
<html>
<body>
<script type="text/javascript">
window.onload = function main() {
var path = "/sndz"; //folder on the webserver for all your sound files
var Hello = document.getElementById("Hello");
Hello.onclick = readWrd(path + "Hello.mp3");
return false;
}
function readWrd(String audioSrc) {
var wrd = new Audio(audioSrc);
wrd.play();
}
</script>
<!--and later in make link or sth-->
<a id="Hello" href="#">Hello</a>
<!--leave the 'href' empty if you want the link to be destroyed after you click it-->
</body>
</html>
All you need to do is add the word at the end of the link below, and then you can style it as much as you want e.g. autoplay when you click a button.
<audio controls="controls">
<source src="http://translate.google.com/translate_tts?tl=en&q=wordgoeshere" type="audio/mpeg">
</audio>

Embed the code on the page and fire the video

I have a few a tags with the name video_button_a
<a id="first_video" class="video_button_a" href="#"></a>
<a id="second_video" class="video_button_a" href="#"></a>
When I click on any of these links i need to embed this in between
<embed
src="http://reelworks.net/player.swf"
width="480"
height="200"
allowscriptaccess="always"
allowfullscreen="true"
flashvars="swfMovie=http://www.reelworks.net/video/runningsahara400x200.flv&swfThumb=http://www.reelworks.net/video/green.jpg&play_btn_scale=.65&playover_color=d7d3c0&playbk_alpha=.65&playbk_color=d7d3c0&play_color=1a1a1a',"
/>
I was thinking append but i didnt know the syntax
$('.video_button_a').click(function(){
// code goes here
});
Is append the way to go and if so how do I start the video, is there a way to put that code on the page and start the video
try this:
$('.video_button_a').click(function(){
$('#player').html('<embed src="http://reelworks.n.... />');
//return false (if you want to)
});
I don't know if you want to embed the code inside the "a" tag which I don't think it is a good idea since it is a flash video - that is why i have a "player" id for a separate div. You could also create something like this:
html
<div id="first_video" class="video_button_div"></div>
<div id="second_video" class="video_button_div"></div>
js
$('.video_button_div').one('click', function() {
$(this).html('<embed src="http://reelworks.n.... />');
//return false (if you want to)
});
css
.video_button_div {
cursor:pointer;
//etc
}
I hope this helps!

Categories

Resources