Html within Javascript - javascript

I am creating a karaoke type website, I simply want to add HTML with the words. I also want to add a break tag so some lyrics are showing on the second page.
The codepen is here:- https://codepen.io/scottYg55/pen/OJPRyXy
As you can see I have tried adding in a break tag, but this isn't outputting as HTML. I understand this, but is there a way to change this?
Can anyone help with this?
var lyricsText = [
{
"text": "Intro <br>Ding Dong Merrily on High",
"duration": 3900
}];
var player = new Vue({
el: '#player',
data: {
lyrics: {
show: false,
timer: null,
currentLine: '',
text: lyricsText,
},
song : {
progress: 0
},
audio: null,
playing: false,
playerTouched: false
},
ready: function() {
// Setup the audio element
this.audio = this.$els.audio;
// Setup time tracker updates
this.audio.addEventListener('timeupdate', this.updateTimeTracker, false);
// Setup end reset
this.audio.addEventListener('ended', this.resetPlayer, false);
},
methods: {
hideText: function() {
this.lyrics.show = !this.lyrics.show;
},
startPlayback: function() {
this.playing = true;
this.audio.volume = 0.5;
this.audio.play();
this.lyrics.show = true;
this.displayNextLine(0);
},
togglePlayback: function() {
if (!this.playerTouched) {
this.startPlayback();
this.playerTouched = true;
return;
}
this.playing = !this.playing;
if (this.audio.paused) {
this.audio.play();
this.resumeLyrics();
} else {
this.audio.pause();
this.pauseLyrics();
}
},
pauseLyrics: function() {
if (this.lyrics.timer) {
this.lyrics.timer.pause();
}
},
resumeLyrics: function() {
if (this.lyrics.timer) {
this.lyrics.timer.resume();
}
},
displayNextLine: function(line) {
var _this = this;
// Set the currentLine, which will auto display
_this.lyrics.currentLine = _this.lyrics.text[line].text;
if (_this.lyrics.text[line + 1] !== undefined) {
_this.lyrics.timer = new Timer(function() {
_this.displayNextLine(line + 1);
}, _this.lyrics.text[line].duration);
}
//else {
// _this.lyrics.currentLine = 'THE END';
//}
},
updateTimeTracker: function() {
this.song.progress = 100 * (this.audio.currentTime / this.audio.duration);
},
resetPlayer: function() {
this.playing = false;
this.playerTouched = false;
}
}
});
function Timer(callback, delay) {
var timerId;
var start;
var remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = function() {
start = new Date();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.0-rc.2/vue.js"></script>
<div class="Player" id="player">
<audio src="dd.mp3"
v-el:audio></audio>
<div class="Player__cover" #click="hideText">
<div class="Player__lyrics">
<div class="line"
v-if="lyrics.show"
v-text="lyrics.currentLine"></div>
</div>
</div>
<div class="Player__track"
:style="{ width: song.progress + '%' }"></div>
<div class="Player__controls">
<i class="icon play material-icons"
v-text="playing ? 'pause_circle_filled' : 'play_circle_filled'"
#click="togglePlayback"></i>
</div>
</div>

Try using v-html directive instead of v-text on your HTML.
<div class="line" v-if="lyrics.show" v-html="lyrics.currentLine"></div>

There are two main ways to create elements in Javascript. The first is to use createElement() function:
const div = document.createElement("div");
div.innerHTML = "I'm a div";
div.id = "myDiv";
document.body.appendChild(div);
#myDiv{
color: red;
}
The second is to use the innerHTML property on an existing element:
const div = document.getElementById("myDiv");
div.innerHTML = "<p>I'm a p tag</p>";
p{
color: green;
}
<div id="myDiv"></div>

Related

Update JS model through MVC not change

i have variables as a model, i were able to change it temporary but when try to update other values it's fetched in the controller but when try to re render it again it show the new value and retrieve the old value quickly,
the issue in updateCat func i think, also i want to pass form is object not each value alone as updated-name and updated-img.
Thanks in advance.
/* ======= Model ======= */
var model = {
currentCat: null,
cats: [
{
clickCount: 0,
name: 'Tabby',
imgSrc: 'img/434164568_fea0ad4013_z.jpg',
imgAttribution: 'https://www.flickr.com/photos/bigtallguy/434164568',
isAdmin: 0
},
{
clickCount: 0,
name: 'Tiger',
imgSrc: 'img/4154543904_6e2428c421_z.jpg',
imgAttribution: 'https://www.flickr.com/photos/xshamx/4154543904',
isAdmin: 0
},
{
clickCount: 0,
name: 'Scaredy',
imgSrc: 'img/22252709_010df3379e_z.jpg',
imgAttribution: 'https://www.flickr.com/photos/kpjas/22252709',
isAdmin: 0
},
{
clickCount: 0,
name: 'Shadow',
imgSrc: 'img/1413379559_412a540d29_z.jpg',
imgAttribution: 'https://www.flickr.com/photos/malfet/1413379559',
isAdmin: 0
},
{
clickCount: 0,
name: 'Sleepy',
imgSrc: 'img/9648464288_2516b35537_z.jpg',
imgAttribution: 'https://www.flickr.com/photos/onesharp/9648464288',
isAdmin: 0
}
]
};
/* ======= Octopus ======= */
var octopus = {
init: function () {
// set our current cat to the first one in the list
model.currentCat = model.cats[0];
// tell our views to initialize
catViewList.init();
catView.init();
},
getCurrentCat: function () {
return model.currentCat;
},
getCats: function () {
return model.cats;
},
// set the currently-selected cat to the object passed in
setCurrentCat: function (cat) {
model.currentCat = cat;
},
// increments the counter for the currently-selected cat
incrementCounter: function () {
model.currentCat.clickCount++;
catView.render();
},
// Admin mode, to edit exist cat (name, url)
showAdminForm: function () {
model.currentCat.isAdmin = 1;
catView.render();
},
updateCat: function (name, img) {
console.log(name + " ----- " + img + " before currentCat " + model.currentCat.name);
model.currentCat.name = name;
model.currentCat.imgSrc = img;
catView.render();
}
};
/* ======= View ======= */
var catView = {
init: function () {
// POINTERS
this.catElem = document.getElementById('cat-div');
this.catNameElem = document.getElementById('cat-name');
this.catCounter = document.getElementById('cat-counter');
this.catImage = document.getElementById('cat-image');
this.isAdmin = document.getElementById('show-admin');
this.adminPanel = document.getElementById('admin-panel');
this.newName = document.getElementById('updated-name');
this.newImg = document.getElementById('updated-name');
this.isAdmin.addEventListener('click', function () {
octopus.showAdminForm();
});
this.catImage.addEventListener('click', function () {
// Get count from octopus
octopus.incrementCounter();
});
this.render();
},
render: function () {
// Empty the form
// this.isAdmin.innerHTML = '';
// update the DOM elements with values from the current cat
var currentCat = octopus.getCurrentCat();
this.catCounter.textContent = currentCat.clickCount;
this.catNameElem.textContent = currentCat.name;
this.catImage.src = currentCat.imgSrc;
this.isAdmin = currentCat.isAdmin;
this.newName.textContent = currentCat.name;
this.newImg.src = currentCat.imgSrc;
this.adminPanel.addEventListener('submit', function() {
var updatedName = document.getElementById("updated-name").value;
var updatedImg = document.getElementById("updated-img").value;
// document.getElementById('cat-name') = updatedName;
octopus.updateCat(updatedName, updatedImg);
// catView.render();
});
if (this.isAdmin == 1) {
this.adminPanel.style.display = "block";
// problem here when changed and re render it fetched old name
// this.adminPanel.addEventListener('submit', function() {
// var updatedName = document.getElementById("updated-name").value;
// var updatedImg = document.getElementById("updated-img").value;
// console.log(updatedName + updatedImg);
// // document.getElementById('cat-name') = updatedName;
// octopus.updateCat(updatedName, updatedImg);
// // catView.render();
// });
} else {
this.adminPanel.style.display = "none";
}
}
};
var catViewList = {
init: function () {
// store the DOM element for easy access later
this.catListElem = document.getElementById('side_nav_item');
// render this view (update the DOM elements with the right values)
this.render();
},
render: function () {
var cat, elem, i;
// get the cats we'll be rendering from the octopus
var cats = octopus.getCats();
// empty the cat list
this.catListElem.innerHTML = '';
// loop over the cats
for (i = 0; i < cats.length; i++) {
// this is the cat we're currently looping over
cat = cats[i];
// make a new cat list item and set its text
elem = document.createElement('a');
elem.textContent = cat.name;
// on click, setCurrentCat and render the catView
// (this uses our closure-in-a-loop trick to connect the value
// of the cat variable to the click event function)
elem.addEventListener('click', (function (catCopy) {
return function () {
octopus.setCurrentCat(catCopy);
catView.render();
};
})(cat));
// finally, add the element to the list
this.catListElem.appendChild(elem);
}
}
};
octopus.init();
<!DOCTYPE html>
<html lang="en">
<head>
<link href="css/main.css" rel="stylesheet">
<!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> -->
<title>Cat List </title>
</head>
<body>
<div class="main">
<div id="side_nav" class="sidenav" >
<li id="side_nav_item" class="side_nav_item"></li>
</div>
<div id="cat-div">
<h2 id="cat-name"></h2>
<div id="cat-counter"></div>
<img id="cat-image" src="" alt="cute cat">
</div>
<button id="show-admin">Admin</button>
<form id="admin-panel">
<label >Name :</label>
<input type="text" id="updated-name">
<label>Img url :</label>
<input type="text" id="updated-img">
<button id="updateCat" type="submit">Save</button>
</form>
<script src="js/model.js"></script>
</div>
</body>
</html>
I found the solution for my silly issue,
this.adminPanel.addEventListener('submit', function(evt) {
var nameToChange = document.getElementById('updated-name').value;
var imgTOChange = document.getElementById('updated-img').value;
console.log(nameToChange + imgTOChange);
octopus.updateCat(nameToChange + imgTOChange);
evt.preventDefault(); // Here is the trick
});
to close.
Thanks.

Jquery Apprise Plugin not working properly

here is my problem :)
i try to add "Apprise-v2" plugin to my website,
i include both files, css and js, this way :
<!--TOP OF MY PAGE-->
<html>
<body>
<link rel="stylesheet" type="text/css" href="css/apprise-v2.css"/>
<!--MY PAGE CONTENTS...-->
...........
<!--BOTTOM OF MY PAGE-->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/raphael-min.js"></script>
<script src="js/tablesorter/jquery.tablesorter.js"></script>
<script src="js/tablesorter/tables.js"></script>
<script type="text/javascript" src="JS/jquery.fancybox.js"></script>
<script type="text/javascript" src="JS/jquery.fancybox.pack.js"></script>
<script src='js/apprise-v2.js'></script>
<script>Apprise("test");</script>
</body>
</html>
my firebug warns me with this :
TypeError: $Apprise is null
if($Apprise.is(':visible')) {
Thanks for help! :)
EDIT : Here is the apprise-v2.js file contents :
// Global Apprise variables
var $Apprise = null,
$overlay = null,
$body = null,
$window = null,
$cA = null,
AppriseQueue = [];
// Add overlay and set opacity for cross-browser compatibility
$(function() {
$Apprise = $('<div class="apprise">');
$overlay = $('<div class="apprise-overlay">');
$body = $('body');
$window = $(window);
$body.append( $overlay.css('opacity', '.94') ).append($Apprise);
});
function Apprise(text, options) {
// Restrict blank modals
if(text===undefined || !text) {
return false;
}
// Necessary variables
var $me = this,
$_inner = $('<div class="apprise-inner">'),
$_buttons = $('<div class="apprise-buttons">'),
$_input = $('<input type="text">');
// Default settings (edit these to your liking)
var settings = {
animation: 700, // Animation speed
buttons: {
confirm: {
action: function() { $me.dissapear(); }, // Callback function
className: null, // Custom class name(s)
id: 'confirm', // Element ID
text: 'Ok' // Button text
}
},
input: false, // input dialog
override: true // Override browser navigation while Apprise is visible
};
// Merge settings with options
$.extend(settings, options);
// Close current Apprise, exit
if(text=='close') {
$cA.dissapear();
return;
}
// If an Apprise is already open, push it to the queue
if($Apprise.is(':visible')) {
AppriseQueue.push({text: text, options: settings});
return;
}
// Width adjusting function
this.adjustWidth = function() {
var window_width = $window.width(), w = "20%", l = "40%";
if(window_width<=800) {
w = "90%", l = "5%";
} else if(window_width <= 1400 && window_width > 800) {
w = "70%", l = "15%";
} else if(window_width <= 1800 && window_width > 1400) {
w = "50%", l = "25%";
} else if(window_width <= 2200 && window_width > 1800) {
w = "30%", l = "35%";
}
$Apprise.css('width', w).css('left', l);
};
// Close function
this.dissapear = function() {
$Apprise.animate({
top: '-100%'
},
settings.animation, function() {
$overlay.fadeOut(300);
$Apprise.hide();
// Unbind window listeners
$window.unbind("beforeunload");
$window.unbind("keydown");
// If in queue, run it
if(AppriseQueue[0]) {
Apprise(AppriseQueue[0].text, AppriseQueue[0].options);
AppriseQueue.splice(0,1);
}
});
return;
};
// Keypress function
this.keyPress = function() {
$window.bind('keydown', function(e) {
// Close if the ESC key is pressed
if(e.keyCode===27) {
if(settings.buttons.cancel) {
$("#apprise-btn-" + settings.buttons.cancel.id).trigger('click');
} else {
$me.dissapear();
}
} else if(e.keyCode===13) {
if(settings.buttons.confirm) {
$("#apprise-btn-" + settings.buttons.confirm.id).trigger('click');
} else {
$me.dissapear();
}
}
});
};
// Add buttons
$.each(settings.buttons, function(i, button) {
if(button) {
// Create button
var $_button = $('<button id="apprise-btn-' + button.id + '">').append(button.text);
// Add custom class names
if(button.className) {
$_button.addClass(button.className);
}
// Add to buttons
$_buttons.append($_button);
// Callback (or close) function
$_button.on("click", function() {
// Build response object
var response = {
clicked: button, // Pass back the object of the button that was clicked
input: ($_input.val() ? $_input.val() : null) // User inputted text
};
button.action( response );
//$me.dissapear();
});
}
});
// Disabled browser actions while open
if(settings.override) {
$window.bind('beforeunload', function(e){
return "An alert requires attention";
});
}
// Adjust dimensions based on window
$me.adjustWidth();
$window.resize( function() { $me.adjustWidth() } );
// Append elements, show Apprise
$Apprise.html('').append( $_inner.append('<div class="apprise-content">' + text + '</div>') ).append($_buttons);
$cA = this;
if(settings.input) {
$_inner.find('.apprise-content').append( $('<div class="apprise-input">').append( $_input ) );
}
$overlay.fadeIn(300);
$Apprise.show().animate({
top: '20%'
},
settings.animation,
function() {
$me.keyPress();
}
);
// Focus on input
if(settings.input) {
$_input.focus();
}
} // end Apprise();
Make call after page loaded.
$(function() {
Apprise('hi there');
});
I think using Apprise V3 is a better idea.
https://github.com/exis9/Apprise_V3

Code is Working on Fiddle but not on Website [duplicate]

This question already has an answer here:
How do I put codes from jsfiddle.net into my website?
(1 answer)
Closed 6 years ago.
This is working fine on Fiddle, but not so fine on my site. I can't seem to figure out the difference.
I've already tried removing the whole Videobox inclusion, and that didn't fix it.
I also realize that jQuery and Mootools is a bit much, but I really like the Videobox, and I really like the audio player.
As far as things working on my site, everything works the way it should, except for the second function in my javascript.
Here's the Fiddle: http://jsfiddle.net/HM8m7/4/
My Site's HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Music</title>
<script type="text/javascript" src="videobox/js/mootools.js"></script>
<script type="text/javascript" src="videobox/js/swfobject.js"></script>
<script type="text/javascript" src="videobox/js/videobox.js"></script>
<link rel="stylesheet" href="videobox/css/videobox.css" type="text/css" media="screen" />
<link rel="stylesheet" href="libs/css/styles.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="src/jquery.ubaplayer.js"></script>
<script>
jQuery.noConflict();
jQuery(function () {
jQuery("#ubaPlayer").ubaPlayer({
codecs: [{
name: "MP3",
codec: 'audio/mpeg;'
}]
});
});
jQuery('a[rel=vidbox]').click(function () {
if (jQuery("#ubaPlayer").ubaPlayer("playing") === true) {
jQuery("#ubaPlayer").ubaPlayer("pause");
}
return false;
});
</script>
</head>
<body>
<div id="content_wrapper">
<div id="table_container">
<table>
<tr>
<th>Title</th>
</tr>
<tr>
<td><div id="ubaPlayer"></div>
<ul class="controls">
<img src="playbtn.png" class="fakeplay" alt="Play Button">The Rainbow Connection (Video)
<ul class="controls">
<li><a class="audioButton" href="mp3/closetoyou.mp3">
Close to You</a></li>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Audio Player Script:
(function($) {
var defaults = {
audioButtonClass: "audioButton",
autoPlay: null,
codecs: [{
name: "OGG",
codec: 'audio/ogg; codecs="vorbis"'
}, {
name: "MP3",
codec: 'audio/mpeg'
}],
continuous: false,
extension: null,
flashAudioPlayerPath: "libs/swf/player.swf",
flashExtension: ".mp3",
flashObjectID: "audioPlayer",
loadingClass: "loading",
loop: false,
playerContainer: "player",
playingClass: "playing",
swfobjectPath: "libs/swfobject/swfobject.js",
volume: 1
},
currentTrack, isPlaying = false,
isFlash = false,
audio, $buttons, $tgt, $el, playTrack, resumeTrack, pauseTrack, methods = {
play: function(element) {
$tgt = element;
currentTrack = _methods.getFileNameWithoutExtension($tgt.attr("href"));
isPlaying = true;
$tgt.addClass(defaults.loadingClass);
$buttons.removeClass(defaults.playingClass);
if (isFlash) {
if (audio) {
_methods.removeListeners(window);
}
audio = document.getElementById(defaults.flashObjectID);
_methods.addListeners(window);
audio.playFlash(currentTrack + defaults.extension);
} else {
if (audio) {
audio.pause();
_methods.removeListeners(audio);
}
audio = new Audio("");
_methods.addListeners(audio);
audio.id = "audio";
audio.loop = defaults.loop ? "loop" : "";
audio.volume = defaults.volume;
audio.src = currentTrack + defaults.extension;
audio.play();
}
},
pause: function() {
if (isFlash) {
audio.pauseFlash();
} else {
audio.pause();
}
$tgt.removeClass(defaults.playingClass);
isPlaying = false;
},
resume: function() {
if (isFlash) {
audio.playFlash();
} else {
audio.play();
}
$tgt.addClass(defaults.playingClass);
isPlaying = true;
},
playing: function() {
return isPlaying;
}
},
_methods = {
init: function(options) {
var types;
//set defaults
$.extend(defaults, options);
$el = this;
//listen for clicks on the controls
$(".controls").bind("click", function(event) {
_methods.updateTrackState(event);
return false;
});
$buttons = $("." + defaults.audioButtonClass);
types = defaults.codecs;
for (var i = 0, ilen = types.length; i < ilen; i++) {
var type = types[i];
if (_methods.canPlay(type)) {
defaults.extension = [".", type.name.toLowerCase()].join("");
break;
}
}
if (!defaults.extension || isFlash) {
isFlash = true;
defaults.extension = defaults.flashExtension;
}
if (isFlash) {
$el.html("<div id='" + defaults.playerContainer + "'/>");
$.getScript(defaults.swfobjectPath, function() {
swfobject.embedSWF(defaults.flashAudioPlayerPath, defaults.playerContainer, "0", "0", "9.0.0", "swf/expressInstall.swf", false, false, {
id: defaults.flashObjectID
}, _methods.swfLoaded);
});
} else {
if (defaults.autoPlay) {
methods.play(defaults.autoPlay);
}
}
},
updateTrackState: function(evt) {
$tgt = $(evt.target);
if (!$tgt.hasClass("audioButton")) {
return;
}
if (!audio || (audio && currentTrack !== _methods.getFileNameWithoutExtension($tgt.attr("href")))) {
methods.play($tgt);
} else if (!isPlaying) {
methods.resume();
} else {
methods.pause();
}
},
addListeners: function(elem) {
$(elem).bind({
"canplay": _methods.onLoaded,
"error": _methods.onError,
"ended": _methods.onEnded
});
},
removeListeners: function(elem) {
$(elem).unbind({
"canplay": _methods.onLoaded,
"error": _methods.onError,
"ended": _methods.onEnded
});
},
onLoaded: function() {
$buttons.removeClass(defaults.loadingClass);
$tgt.addClass(defaults.playingClass);
audio.play();
},
onError: function() {
$buttons.removeClass(defaults.loadingClass);
if (isFlash) {
_methods.removeListeners(window);
} else {
_methods.removeListeners(audio);
}
},
onEnded: function() {
isPlaying = false;
$tgt.removeClass(defaults.playingClass);
currentTrack = "";
if (isFlash) {
_methods.removeListeners(window);
} else {
_methods.removeListeners(audio);
}
if (defaults.continuous) {
var $next = $tgt.next().length ? $tgt.next() : $(defaults.audioButtonClass).eq(0);
methods.play($next);
}
},
canPlay: function(type) {
if (!document.createElement("audio").canPlayType) {
return false;
} else {
return document.createElement("audio").canPlayType(type.codec).match(/maybe|probably/i) ? true : false;
}
},
swfLoaded: function() {
if (defaults.autoPlay) {
setTimeout(function() {
methods.play(defaults.autoPlay);
}, 500);
}
},
getFileNameWithoutExtension: function(fileName) {
//this function take a full file name and returns an extensionless file name
//ex. entering foo.mp3 returns foo
//ex. entering foo returns foo (no change)
var fileNamePieces = fileName.split('.');
fileNamePieces.pop();
return fileNamePieces.join(".");
}
};
$.fn.ubaPlayer = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
return _methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist on jquery.ubaPlayer");
}
};})(jQuery);
Videobox Script:
var Videobox = {
init: function (options) {
// init default options
this.options = Object.extend({
resizeDuration: 400, // Duration of height and width resizing (ms)
initialWidth: 250, // Initial width of the box (px)
initialHeight: 250, // Initial height of the box (px)
defaultWidth: 625, // Default width of the box (px)
defaultHeight: 350, // Default height of the box (px)
animateCaption: true, // Enable/Disable caption animation
flvplayer: 'swf/flvplayer.swf'
}, options || {});
this.anchors = [];
$A($$('a')).each(function(el){
if(el.rel && el.href && el.rel.test('^vidbox', 'i')) {
el.addEvent('click', function (e) {
e = new Event(e);
e.stop();
this.click(el);
}.bind(this));
this.anchors.push(el);
}
}, this);
this.overlay = new Element('div').setProperty('id', 'lbOverlay').injectInside(document.body);
this.center = new Element('div').setProperty('id', 'lbCenter').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);
this.bottomContainer = new Element('div').setProperty('id', 'lbBottomContainer').setStyle('display', 'none').injectInside(document.body);
this.bottom = new Element('div').setProperty('id', 'lbBottom').injectInside(this.bottomContainer);
new Element('a').setProperties({id: 'lbCloseLink', href: '#'}).injectInside(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
this.caption = new Element('div').setProperty('id', 'lbCaption').injectInside(this.bottom);
this.number = new Element('div').setProperty('id', 'lbNumber').injectInside(this.bottom);
new Element('div').setStyle('clear', 'both').injectInside(this.bottom);
var nextEffect = this.nextEffect.bind(this);
this.fx = {
overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
center: this.center.effects({duration: 500, transition: Fx.Transitions.sineInOut, onComplete: nextEffect}),
bottom: this.bottom.effect('margin-top', {duration: 400})
};
},
click: function(link) {
return this.open (link.href, link.title, link.rel);
},
open: function(sLinkHref, sLinkTitle, sLinkRel) {
this.href = sLinkHref;
this.title = sLinkTitle;
this.rel = sLinkRel;
this.position();
this.setup();
this.video(this.href);
this.top = Window.getScrollTop() + (Window.getHeight() / 15);
this.center.setStyles({top: this.top+'px', display: ''});
this.fx.overlay.start(0.8);
this.step = 1;
this.center.setStyle('background','#fff url(loading.gif) no-repeat center');
this.caption.innerHTML = this.title;
this.fx.center.start({'height': [this.options.contentsHeight]});
},
setup: function(){
var aDim = this.rel.match(/[0-9]+/g);
this.options.contentsWidth = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defaultWidth;
this.options.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defaultHeight;
},
position: function(){
this.overlay.setStyles({'top': window.getScrollTop()+'px', 'height': window.getHeight()+'px'});
},
video: function(sLinkHref){
if (sLinkHref.match(/youtube\.com\/watch/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('=');
this.videoID = videoId[1];
this.so = new SWFObject("http://www.youtube.com/v/"+this.videoID, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/metacafe\.com\/watch/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('/');
this.videoID = videoId[4];
this.so = new SWFObject("http://www.metacafe.com/fplayer/"+this.videoID+"/.swf", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/google\.com\/videoplay/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('=');
this.videoID = videoId[1];
this.so = new SWFObject("http://video.google.com/googleplayer.swf?docId="+this.videoID+"&hl=en", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/ifilm\.com\/video/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('video/');
this.videoID = videoId[1];
this.so = new SWFObject("http://www.ifilm.com/efp", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0", "#000");
this.so.addVariable("flvbaseclip", this.videoID+"&");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/\.mov/i)) {
this.flash = false;
if (navigator.plugins && navigator.plugins.length) {
this.other ='<object id="qtboxMovie" type="video/quicktime" codebase="http://www.apple.com/qtactivex/qtplugin.cab" data="'+sLinkHref+'" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'"><param name="src" value="'+sLinkHref+'" /><param name="scale" value="aspect" /><param name="controller" value="true" /><param name="autoplay" value="true" /><param name="bgcolor" value="#000000" /><param name="enablejavascript" value="true" /></object>';
} else {
this.other = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'" id="qtboxMovie"><param name="src" value="'+sLinkHref+'" /><param name="scale" value="aspect" /><param name="controller" value="true" /><param name="autoplay" value="true" /><param name="bgcolor" value="#000000" /><param name="enablejavascript" value="true" /></object>';
}
}
else if (sLinkHref.match(/\.wmv/i) || sLinkHref.match(/\.asx/i)) {
this.flash = false;
this.other = '<object NAME="Player" WIDTH="'+this.options.contentsWidth+'" HEIGHT="'+this.options.contentsHeight+'" align="left" hspace="0" type="application/x-oleobject" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"><param NAME="URL" VALUE="'+sLinkHref+'"><param><param NAME="AUTOSTART" VALUE="false"></param><param name="showControls" value="true"></param><embed WIDTH="'+this.options.contentsWidth+'" HEIGHT="'+this.options.contentsHeight+'" align="left" hspace="0" SRC="'+sLinkHref+'" TYPE="application/x-oleobject" AUTOSTART="false"></embed></object>'
}
else if (sLinkHref.match(/\.flv/i)) {
this.flash = true;
this.so = new SWFObject(this.options.flvplayer+"?file="+sLinkHref, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0", "#000");
}
else {
this.flash = true;
this.videoID = sLinkHref;
this.so = new SWFObject(this.videoID, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
}
},
nextEffect: function(){
switch (this.step++){
case 1:
this.fx.center.start({'width': [this.options.contentsWidth], 'marginLeft': [this.options.contentsWidth/-2]});
break;
this.step++;
case 2:
this.center.setStyle('background','#fff');
this.flash ? this.so.write(this.center) : this.center.setHTML(this.other) ;
this.bottomContainer.setStyles({top: (this.top + this.center.clientHeight)+'px', height: '0px', marginLeft: this.center.style.marginLeft, width: this.options.contentsWidth+'px',display: ''});
if (this.options.animateCaption){
this.fx.bottom.set(-this.bottom.offsetHeight);
this.bottomContainer.style.height = '';
this.fx.bottom.start(0);
break;
}
this.bottomContainer.style.height = '';
this.step++;
}
},
close: function(){
this.fx.overlay.start(0);
this.center.style.display = this.bottomContainer.style.display = 'none';
this.center.innerHTML = '';
return false;
}};window.addEvent('domready', Videobox.init.bind(Videobox));
Your website JS code needs to wait for DOM ready before the jQuery can find the #ubaPlayer and a[rel=vidbox] elements (This is because your script is declared before the HTML, you could get away with it if your script was defined after the html, albeit not a great idea because you really should have your JavaScript in a external .js file).
So, wrap it with .ready() so that your scripts run after the DOM is ready:
jQuery(document).ready(function () {
jQuery("#ubaPlayer").ubaPlayer({
codecs: [{
name: "MP3",
codec: 'audio/mpeg;'
}]
});
jQuery('a[rel=vidbox]').click(function () {
if (jQuery("#ubaPlayer").ubaPlayer("playing") === true) {
jQuery("#ubaPlayer").ubaPlayer("pause");
}
return false;
});
});
The fiddle has on DOM ready, so it works.

codemirror - ondblclick only affecting last element with class

http://jsfiddle.net/tZVsS/72/
if you double-click either of the first two elements with the class .code you'll notice that the setOptions will only be applied to the last element with the class .code. what i need to happen is when you double-click on each individual elements the setoption to be applied to that element, why is this not working and what can be done to fix it
(function () {
var codes = document.getElementsByClassName("code");
for (i = 0; i < codes.length; i++) {
var $this = codes[i];
var $unescaped = $this.innerHTML.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
var isspan = $this.nodeName.toLowerCase() == "span";
$this.innerHTML = "";
if (isspan) {
$this.style.display = "inline-block"
} else {
$this.style.display = "inline"
}
var editor = new CodeMirror($this, {
value: $unescaped,
mode: 'javascript',
lineNumbers: false,
readOnly: true
});
$this.ondblclick = function () {
editor.setOption("readOnly", false);
editor.setOption("lineNumbers", true);
}
}
})();
The HTML is below, NOTE: it's not much use, instead retrace what i've done on the fiddle for a good understanding
Some code <span class="code inline">function inline() { alert('inline code') }</span> inside
a sentence.
<div class="code">function test() { return false; }</div>
Just a scope issue
Updated Fiddle: http://jsfiddle.net/tZVsS/73/
(function () {
var codes = document.getElementsByClassName("code");
for (i = 0; i < codes.length; i++) {
(function ($this) {
var $unescaped = $this.innerHTML.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
var isspan = $this.nodeName.toLowerCase() == "span";
$this.innerHTML = "";
if (isspan) {
$this.style.display = "inline-block"
} else {
$this.style.display = "inline"
}
var editor = new CodeMirror($this, {
value: $unescaped,
mode: 'javascript',
lineNumbers: false,
readOnly: true
});
$this.ondblclick = function () {
console.log($this);
editor.setOption("readOnly", false);
editor.setOption("lineNumbers", true);
}
})(codes[i]);
}
})();

Point to html page after last slide of html5 gallery

I've a problem with a html5 gallery.
This gallery must point to a html page after last slide transition.
I have 3 slides (a sort of splash composed by images) and after the third image I want to redirect on my website's home page.
<div class="slider">
<figure class="active">
<img src="gallery/hp-1.jpg" onload="imageLoaded();" alt="image 1" />
</figure>
<figure>
<img src="gallery/hp-2.jpg" alt="image 2" />
</figure>
<figure>
<img src="gallery/hp-3.jpg" alt="image 3" />
</figure>
</div>
<script>
(function($, window, document, undefined) {
var Html5Gallery = {
isTransitionInProgress : false,
isMusicPlaying : false,
fMusicPlayer : null,
nextSwitch : null,
fMusicPlayerIsLoaded : false,
isWindowReady : false,
imageIsStillLoading : true,
init : function(element, options)
{
var self = this;
$(window).ready(function(){
self.isWindowReady = true;
if (!self.imageIsStillLoading) {
self.handleReadness();
}
});
this.options = $.fn.extend({}, $.fn.Html5Gallery.options, options);
this.imageIsStillLoading = true;
$(window).bind("resize", this.handleResizing);
window.flashIsLoaded = function() {
self.flashPlayerLoaded();
};
window.imageLoaded = function() {
if(!$("figure.active img").get(0).complete)
{
self.isTransitionInProgress = true;
setTimeout(imageLoaded, 100);
return;
}
self.imageIsStillLoading = false;
if (self.isWindowReady) {
self.handleReadness();
}
};
},
nextImage: function(e)
{
if (this.isTransitionInProgress)
{
return;
}
this.cancelNextScheduledImage();
var from = $("figure.active");
var to = (from.next().is("figure") ? from.next() : from.parent().children(":first"));
this.isTransitionInProgress = true;
this.switchImages(from, to);
},
prevImage: function(e)
{
if (this.isTransitionInProgress)
return;
var from = $("figure.active");
var to = (from.prev().is("figure") ? from.prev() : from.parent().children(":last"));
this.isTransitionInProgress = true;
this.switchImages(from, to);
},
switchImages: function(from, to)
{
var self = this;
var isNextImageLoaded = to.children("img").get(0).complete;
if (isNextImageLoaded)
{
from.stop().fadeOut(self.options.transitionSpeed, function(){
from.removeClass("active").css("display", "none");
to.addClass("active");
self.handleResizing();
to.hide().fadeIn(self.options.transitionSpeed, function(){
self.isTransitionInProgress = false;
self.scheduleNextImage();
});
});
return;
}
$("#loading").hide().fadeIn(self.options.transitionSpeed, function(){
from.removeClass("active").css("display", "none");
to.addClass("active");
if (isNextImageLoaded)
{
self.handleResizing();
self.hideLoading();
}
else
{
imageLoaded();
}
});
},
hideLoading: function()
{
var self = this;
$("#loading").fadeOut(this.options.transitionSpeed, function(){
self.isTransitionInProgress = false;
self.scheduleNextImage();
});
},
cancelNextScheduledImage: function()
{
clearTimeout(this.nextSwitch);
this.nextSwitch = null;
},
scheduleNextImage: function()
{
var self = this;
this.cancelNextScheduledImage();
if (!this.isTransitionInProgress && this.options.autoSwitch)
{
this.nextSwitch = setTimeout(function(){
self.nextImage();
}, this.options.pauseOnPictureFor);
}
},
};
})
</script>
You can download here the html file complete with all code.
Thank you for your help.
Simone
You can hook into the logic which loops back to the first slide. This works by checking whether the next element is a figure element and, if not, grabbing the first figure element and switching to it. You can override this logic to redirect your page after the last slide has displayed like so (not tested):
nextImage: function(e)
{
if (this.isTransitionInProgress)
{
return;
}
this.cancelNextScheduledImage();
var from = $("figure.active");
// var to = (from.next().is("figure"); ? from.next() : from.parent().children(":first"));
var to = from.next();
if (to.is("figure")) {
this.isTransitionInProgress = true;
this.switchImages(from, to);
} else {
window.location.replace("http://stackoverflow.com");
}
},
I've hardcoded the URL in place for speed and clarity, but a better approach would be to pass the URL to the plugin via the options object it receives as a parameter of the init method.

Categories