How to dynamically change YouTube player's options - javascript

I have a chatroom and I'm making it better for practice purposes; there's already socket.io running on a node.js server, but I decided to make my own radio.
Here is the code belonging to the radio:
HTML:
<div data-video="1cDxhcAOpa8"
data-autoplay="1"
data-loop="1"
id="youtube-audio">
<form id="formMusica">
<select id="selectGenero">
<option value="edm" selected>EDM</option>
<option value="rock">Rock</option>
</select>
</form>
<script src="https://www.youtube.com/iframe_api"></script>
<script id="scriptYt" src="/yt.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var $container = $('#youtube-audio');
var $formGenero = $('#formMusica');
var $select = $('#selectGenero');
var $genero;
$formGenero.submit(function (e) {
e.preventDefault();
});
$select.change(function () {
$genero = $select.val();
buildPlayer();
});
var radios = [{
'name': 'Pixl',
'genre': 'EDM',
'type': 'video',
'ytd_id': 'cDxhcAOpa8'
}, {
'name': 'Best Rock Music',
'genre': 'Rock',
'type': 'playlist',
'ytd_id': 'PLZN_exA7d4RVmCQrG5VlWIjMOkMFZVVOc'
}];
function buildPlayer() {
var genreData = getGenreData();
// Erase all to build again
$container.html('');
if (genreData.type === 'video') {
$container.attr('data-video', genreData.ytd_id)
.removeAttr('data-listtype').removeAttr('data-list');
}
else if (genreData.type === 'playlist') {
$container.attr('data-list', genreData.ytd_id)
.attr('data-listtype', genreData.type).removeAttr('data-video');
}
// #scriptYt's code will be below
$('#scriptYt').remove();
$('body').append('<script id="scriptYt" src="/yt.js"><\/script>');
onYouTubeIframeAPIReady();
}
function getGenreData() {
for (i = 0; i < radios.length; i++) {
if (radios[i].genre.toLowerCase() === $genero) {
return radios[i];
}
}
}
});
</script>
YT.JS:
var r;
function onYouTubeIframeAPIReady() {
var $container = $('#youtube-audio');
$container.append('<i class="fa fa-2x" id="youtube-icon"></i>');
var $icon = $('#youtube-icon');
$icon.css({ 'transition': '0.5s', 'cursor': 'pointer' });
$container.append('<div id="youtube-player"></div>');
var o = function (e) {
var a = e ? 'fa-stop' : 'fa-play';
if (a === 'fa-stop') {
$icon.addClass('fa-stop');
$icon.addClass('text-danger');
$icon.removeClass('fa-play');
$icon.removeClass('text-success');
}
else if (a === 'fa-play') {
$icon.addClass('fa-play');
$icon.addClass('text-success');
$icon.removeClass('fa-stop');
$icon.removeClass('text-danger');
}
};
$container.click(function () {
r.getPlayerState() === YT.PlayerState.PLAYING || r.getPlayerState() === YT.PlayerState.BUFFERING ? (r.pauseVideo(), o(!1)) : (r.playVideo(), o(!0));
});
r = new YT.Player('youtube-player', {
height: '0',
width: '0',
videoId: $container.data('video'),
playerVars: {
listType: $container.data('listtype'),
list:$container.data('list'),
autoplay: $container.data('autoplay'),
loop: $container.data('loop')
},
events: {
onReady: function (e) {
r.setPlaybackQuality('small'),
o(r.getPlayerState !== YT.PlayerState.CUED)
},
onStateChange: function (e) {
e.data === YT.PlayerState.ENDED && o(!1)
}
}
});
}
It works perfectly when you first load the page, then when you select other genre it stays the same video, I tried removing everything inside #youtube-audio and the script tag, then inserting the tag again and calling the method, it loads the same video every time.
OBS: I know JavaScript well, but I prefer jQuery if possible.
UPDATE: Thanks to #matthewninja, r.loadVideoById() works, but still I need to work with playlists, r.loadPlaylist() doesn't work.

There's no need to destroy the previously existing player element in order to change the video. According to the YouTube Player API Reference page, you can simply call player.loadVideoById(videoId) to change the song.
With that being said, here's a solution that I've implemented using a button that changes the song:
HTML
<html>
<head>
<script
src="http://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
</head>
<body>
<div data-video="1cDxhcAOpa8"
data-autoplay="1"
data-loop="1"
id="youtube-audio">
<button onclick="changeSong()">change song</button>
<script src="https://www.youtube.com/iframe_api"></script>
<script id="scriptYt" src="yt.js"></script>
</div>
</body>
</html>
yt.js
var r;
function onYouTubeIframeAPIReady() {
var $container = $('#youtube-audio');
$container.append('<i class="fa fa-2x" id="youtube-icon"></i>');
var $icon = $('#youtube-icon');
$icon.css({ 'transition': '0.5s', 'cursor': 'pointer' });
$container.append('<div id="youtube-player"></div>');
var o = function (e) {
var a = e ? 'fa-stop' : 'fa-play';
if (a === 'fa-stop') {
$icon.addClass('fa-stop');
$icon.addClass('text-danger');
$icon.removeClass('fa-play');
$icon.removeClass('text-success');
}
else if (a === 'fa-play') {
$icon.addClass('fa-play');
$icon.addClass('text-success');
$icon.removeClass('fa-stop');
$icon.removeClass('text-danger');
}
};
$container.click(function () {
r.getPlayerState() === YT.PlayerState.PLAYING || r.getPlayerState() === YT.PlayerState.BUFFERING ? (r.pauseVideo(), o(!1)) : (r.playVideo(), o(!0));
});
r = new YT.Player('youtube-player', {
height: '0',
width: '0',
videoId: $container.data('video'),
playerVars: {
listType: $container.data('listtype'),
list:$container.data('list'),
autoplay: $container.data('autoplay'),
loop: $container.data('loop')
},
events: {
onReady: function (e) {
r.setPlaybackQuality('small'),
o(r.getPlayerState !== YT.PlayerState.CUED)
},
onStateChange: function (e) {
e.data === YT.PlayerState.ENDED && o(!1)
}
}
});
}
function changeSong(){
r.loadVideoById("mHpZ-ZFZwiY");
}
When the user clicks the button, the video will change to a video specified by the argument given to loadVideoById. Given this functionality, you should have a much easier time implementing your ideal solution. You could modify your changeSong() function to accept an argument from a <select> element.

Related

How do I make tinyMCE editor stay in my jQgrid textarea formedit form after first initialize?

I have a jqgrid that I am trying to use tinyMCE in the text area to send/store html in my database and reload to my grid. I have a custom column with tinyMCE for the text area but after I open editform once and close it next time it is opened tinymce does not initialize and a regular textarea appears. (Also when url modal it looses focus and focuses on editform. The text is pasted to the back "Project" field instead(picture below).)What I'm I doing wrong?
Reason why my TineMCE "Links" was losing focus was because of a simple syntax error. I had modal:true in the editgrid code.
UPDATE FOR WORKING INLINE EDIT IMPLEMENTATION
Here are examples for correct implementation for inline edit(Thank you #Oleg): DEMO1 | DEMO2
INLINE EDIT WORKING CODE SAMPLE:
{ name: "note", width: 260, sortable: false, editable: true,
//edittype: "textarea"
edittype:'custom',
editoptions: {
custom_element: function (value, options) {
var elm = $("<textarea></textarea>");
elm.val(value);
// give the editor time to initialize
setTimeout(function () {
try {
tinymce.remove("#" + options.id);
} catch(ex) {}
tinymce.init({selector: "#" + options.id, plugins: "link"});
}, 50);
return elm;
},
custom_value: function (element, oper, gridval) {
var id;
if (element.length > 0) {
id = element.attr("id");
} else if (typeof element.selector === "string") {
var sels = element.selector.split(" "),
idSel = sels[sels.length - 1];
if (idSel.charAt(0) === "#") {
id = idSel.substring(1);
} else {
return "";
}
}
if (oper === "get") {
return tinymce.get(id).getContent({format: "row"});
} else if (oper === "set") {
if (tinymce.get(id)) {
tinymce.get(id).setContent(gridval);
}
}
}}
}
jqGrid column:
<script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
<script src="tinymce/tinymce.min.js"type="text/javascript"></script>
<script src="tinymce/jquery.tinymce.min.js"type="text/javascript"></script>
<script src= "tinymce/plugins/link/plugin.min.js" type="text/javascript"></script>
<script type="text/javascript">
...
{ name:'notes',
index:'notes',
edittype:'custom', editable:true,
editoptions:{
"custom_element":function( value , options) {
var elm = $('<textarea></textarea>');
elm.val( value );
// give the editor time to initialize
setTimeout( function() {
tinymce.init({selector: "textarea#notes",plugins: "link"});
}, 100);
return elm;
},
"custom_value":function( element, oper, gridval) {
if(oper === 'get') {
return tinymce.get('notes').getContent({format: 'row'});
} else if( oper === 'set') {
if(tinymce.get('notes')) {
tinymce.get('notes').setContent( gridval );
}
}
}}}
Try to replace the code of custom_element to the following
custom_element: function (value, options) {
var elm = $("<textarea></textarea>");
elm.val(value);
// give the editor time to initialize
setTimeout(function () {
try {
tinymce.remove("#" + options.id);
} catch(ex) {}
tinymce.init({selector: "#" + options.id, plugins: "link"});
}, 50);
return elm;
}
One more simpel

Youtube Video Autoplay in popup

I've made a popup and placed a youtube video in it. I set video to autoplay. But the problem is video plays when i open the page. It is auto play in global and i want it to autoplay when popup shows. I did not find any solution for it.
Currently, It playing like i have background ghost saying something.
Can anyone help?
Video Html
<iframe width="800" height="315" src="http://www.youtube.com/embed/?wmode=opaque&autoplay=1&rel=0&color=white" frameborder="0"></iframe><img alt="" class="watermark" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQHcbyVSjHQlwCy3tYqOyLwSWDO4tblhxTVVjKV5R0PtFsPy9TwfA" /></div>
</div>
Calling popup
<img src="kaow.png"/>
</div>
Popup Content
<div id="video_pop" class="reveal-modal medium">
<a class="close-reveal-modal"></a>
<div>
<iframe width="800" height="315" src="http://www.youtube.com/embed/?wmode=opaque&autoplay=1&rel=0&color=white" frameborder="0"></iframe><img alt="" class="watermark" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQHcbyVSjHQlwCy3tYqOyLwSWDO4tblhxTVVjKV5R0PtFsPy9TwfA" /></div>
</div>
JS
Foundation.libs.reveal = {
name: "reveal",
version: "4.2.2",
locked: !1,
settings: {
animation: "fadeAndPop",
animationSpeed: 250,
closeOnBackgroundClick: !0,
closeOnEsc: !0,
dismissModalClass: "close-reveal-modal",
bgClass: "reveal-modal-bg",
open: function() {},
opened: function() {},
close: function() {},
closed: function() {},
bg: a(".reveal-modal-bg"),
css: {
open: {
opacity: 0,
visibility: "visible",
display: "block"
},
close: {
opacity: 1,
visibility: "hidden",
display: "none"
}
}
},
init: function(b, c, d) {
return Foundation.inherit(this, "data_options delay"), "object" == typeof c ? a.extend(!0, this.settings, c) : "undefined" != typeof d && a.extend(!0, this.settings, d),
"string" != typeof c ? (this.events(), this.settings.init) : this[c].call(this, d);
},
events: function() {
var b = this;
return a(this.scope).off(".fndtn.reveal").on("click.fndtn.reveal", "[data-reveal-id]", function(c) {
c.preventDefault();
if (!b.locked) {
var d = a(this), e = d.data("reveal-ajax");
b.locked = !0;
if ("undefined" == typeof e) b.open.call(b, d); else {
var f = e === !0 ? d.attr("href") : e;
b.open.call(b, d, {
url: f
});
}
}
}).on("click.fndtn.reveal", this.close_targets(), function(c) {
c.preventDefault();
if (!b.locked) {
var d = a.extend({}, b.settings, b.data_options(a(".reveal-modal.open")));
if (a(c.target)[0] === a("." + d.bgClass)[0] && !d.closeOnBackgroundClick) return;
b.locked = !0, b.close.call(b, a(this).closest(".reveal-modal"));
}
}).on("open.fndtn.reveal", ".reveal-modal", this.settings.open).on("opened.fndtn.reveal", ".reveal-modal", this.settings.opened).on("opened.fndtn.reveal", ".reveal-modal", this.open_video).on("close.fndtn.reveal", ".reveal-modal", this.settings.close).on("closed.fndtn.reveal", ".reveal-modal", this.settings.closed).on("closed.fndtn.reveal", ".reveal-modal", this.close_video),
a("body").bind("keyup.reveal", function(c) {
var d = a(".reveal-modal.open"), e = a.extend({}, b.settings, b.data_options(d));
27 === c.which && e.closeOnEsc && d.foundation("reveal", "close");
}), !0;
},
open: function(b, c) {
if (b) if ("undefined" != typeof b.selector) var d = a("#" + b.data("reveal-id")); else {
var d = a(this.scope);
c = b;
} else var d = a(this.scope);
if (!d.hasClass("open")) {
var e = a(".reveal-modal.open");
"undefined" == typeof d.data("css-top") && d.data("css-top", parseInt(d.css("top"), 10)).data("offset", this.cache_offset(d)),
d.trigger("open"), e.length < 1 && this.toggle_bg(d);
if ("undefined" == typeof c || !c.url) this.hide(e, this.settings.css.close), this.show(d, this.settings.css.open); else {
var f = this, g = "undefined" != typeof c.success ? c.success : null;
a.extend(c, {
success: function(b, c, h) {
a.isFunction(g) && g(b, c, h), d.html(b), a(d).foundation("section", "reflow"),
f.hide(e, f.settings.css.close), f.show(d, f.settings.css.open);
}
}), a.ajax(c);
}
}
},
close: function(b) {
var b = b && b.length ? b : a(this.scope), c = a(".reveal-modal.open");
c.length > 0 && (this.locked = !0, b.trigger("close"), this.toggle_bg(b), this.hide(c, this.settings.css.close));
},
close_targets: function() {
var a = "." + this.settings.dismissModalClass;
return this.settings.closeOnBackgroundClick ? a + ", ." + this.settings.bgClass : a;
},
toggle_bg: function(b) {
0 === a(".reveal-modal-bg").length && (this.settings.bg = a("<div />", {
"class": this.settings.bgClass
}).appendTo("body")), this.settings.bg.filter(":visible").length > 0 ? this.hide(this.settings.bg) : this.show(this.settings.bg);
},
EDITED:
I am using Foundation 5 Reveal Model for popup: http://foundation.zurb.com/docs/components/reveal.html
I think you want something like that :
LIVE EXAMPLE
Basically i use the API Javascript to add actions play and pause to the video.
And i use default function of Foundation to add an event when to the player.
HTML
Click Me For A Modal
<div id="myModal" class="reveal-modal" data-reveal>
<h2>Awesome</h2>
<div id="player"></div>
<a class="close-reveal-modal">×</a>
</div>
JS
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '315',
width: '560',
videoId: 'l-gQLqv9f4o',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
//player is playing
} else {
//player is paused
}
}
function stopVideo() {
player.stopVideo();
}
function playVideo() {
player.playVideo();
}
function pauseVideo() {
player.pauseVideo();
}
$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
playVideo();
});
$(document).on('closed.fndtn.reveal', '[data-reveal]', function () {
pauseVideo();
});
From the YouTube JavaScript Player API Reference:
The JavaScript API allows users to control the YouTube chromeless or
embedded video players via JavaScript. Calls can be made to play,
pause, seek to a certain time in a video, set the volume, mute the
player, and other useful functions.
You can use the API's player.playVideo(), player.pauseVideo() and player.stopVideo() method.
So, Ive read a bunch of different threads on this and most of what Ive seen is pretty complicated. I went a much more simple route.
$('.reveal-overlay').click(function(e){
var loc = document.getElementById('myFrame').src;
var stoploc = loc.replace("?autoplay=1", "");
document.getElementById('myFrame').setAttribute('src', stoploc);
});
$('.playVideo').click(function(e){
var loc = document.getElementById('myFrame').src;
var autoloc = loc + "?autoplay=1";
document.getElementById('myFrame').setAttribute('src', autoloc);
});
This will basically just append ?autoplay=1 to a YouTube video once the modal is opened. The class .playVideo is on whatever button youre using to open your modal window.
The class .reveal-overlay is created by Foundation. So when the overlay is clicked it removes any ?autoplay=1 from the video url.
Hope this helps anyone running into this problem. It's simple and should work for multiple different videos, plus, if someone has js turned off, it won't play anything in the background.
One more thing, the video you load should be a regular non-autoplay video. This will turn it into an autoplay after clicked ony and return it to non-autoplay when closed.
Thanks to #Jarod Means script! It works and I uses it since it only requires jQuery (Simple solution = Great solution). But I developed it for multiple video clips, which is great in slideshows, as an example or whenever you need this solution for more then one clip in the same dom. I also made it so it is completely in jQuery.
Just posting it so you can use it as you wish.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<meta charset="utf-8">
<title>Youtube-player test</title>
<style>
.youtube-player iframe {
display: none;
}
.youtube-player.active iframe {
display: block;
}
</style>
</head>
<body>
<div class="youtube-player">
<iframe width="560" height="315" src="https://www.youtube.com/embed/XzXjuDM_Z54" frameborder="0" allowfullscreen></iframe>
Open window
Close window
</div>
<div class="youtube-player">
<iframe width="560" height="315" src="https://www.youtube.com/embed/l2EYyzXJIdE" frameborder="0" allowfullscreen></iframe>
Open window
Close window
</div>
<script>
jQuery('.youtube-player').each(function(){
jQuery(this).on('click', '.youtube-link-start', function(){
jQuery(this).parent().addClass('active');
var loc = $(this).siblings('iframe').attr('src');
var startloc = loc + "?autoplay=1";
$(this).siblings('iframe').attr('src', startloc);
});
jQuery(this).on('click', '.youtube-link-stop', function(){
jQuery(this).parent().removeClass('active');
var loc = $(this).siblings('iframe').attr('src');
var stoploc = loc.replace("?autoplay=1", "");
$(this).siblings('iframe').attr('src', stoploc);
});
});
</script>
</body>
</html>
I guess you can keep on changing/developing this with html, css and jQuery to whatever fit your needs. :)

loading my script using getScript

at first I'm loading all my js script in my header and it's all working properly. But I have one js file that need to be loaded inline/ load it in a certain page only.
this is the js file that I need to load
var myScroll,pullDownEl, pullDownOffset, generatedCount = 0;
function pullDownAction () {
setTimeout(function () {
var el, li, i;
el = document.getElementById('newlist');
if ( el.hasChildNodes() ) {
while ( el.childNodes.length >= 1 ) {
el.removeChild( el.firstChild );
}
}
for (i=0; i<6; i++) {
li = document.createElement('li');
li.innerText = 'Generated row ' + (++generatedCount);
el.insertBefore(li, el.childNodes[0]);
}
myScroll.refresh();
}, 1000);
}
function loaded() {
pullDownEl = document.getElementById('pullDown');
pullDownOffset = pullDownEl.offsetHeight;
myScroll = new iScroll('wrapper', {
//hideScrollbar: false,
//hScrollbar: false, vScrollbar: false, vScroll: false,
useTransition: true,
topOffset: pullDownOffset,
onRefresh: function () {
if (pullDownEl.className.match('loading')) {
pullDownEl.className = '';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
$('#pullDown').css('display', 'inherit');
$('#pullDown').css('display', 'none');
$('#thelist').css('display', 'none');
$('#newlist').css('display', 'inherit');
}
},
onScrollMove: function () {
if (this.y > 5 && !pullDownEl.className.match('flip')) {
pullDownEl.className = 'flip';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Release to refresh...';
$('#pullDown').css('display', 'inherit');
this.minScrollY = 0;
} else if (this.y < 5 && pullDownEl.className.match('flip')) {
pullDownEl.className = '';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
$('#pullDown').css('display', 'inherit');
this.minScrollY = -pullDownOffset;
}
},
onScrollEnd: function () {
if (pullDownEl.className.match('flip')) {
pullDownEl.className = 'loading';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Loading...';
pullDownAction();
}
}
});
setTimeout(function () { document.getElementById('wrapper').style.left = '0'; }, 800);
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
loading it with my other script in my header it works but now I'm using the jquery getScript. It loads the script (using firebug) but when I tried calling the functions inside my js file it give me a two errors
Cannot read property 'offsetHeight' of null
Cannot call method 'refresh' of undefined
This is how I call my js script using getScript
$(document).ready(function() {
$('.email').click(function (){
$.getScript("assets/js/scroll.js",function() {
pullDownAction();
loaded();
});
});
});
Help anyone
I know this may suggest more work than you want to do, but have you tried doing namespacing? I do not know if this works 100% (as i am not sure of the reasoning why that is not working for you), but have you tried this?
(function( PullDown, $, undefined ) {
//Private variables and this is a great way for minification, you will get the most out of it
var myScroll,pullDownEl, pullDownOffset, generatedCount = 0;
function pullDownAction () {
//... your stuff here
}
function loaded() {
//... more your stuff here
}
}(window.PullDown = window.PullDown || {}, jQuery) // avoids name space collision w/ jQuery
Now do the same things, but with this edit.
$(document).ready(function() {
$('.email').click(function (){
$.getScript("assets/js/scroll.js",function() {
window.PullDown.pullDownAction();
window.PullDown.loaded();
});
});
});
If i am not mistaken, or have bad copy and paste skills, this should work out just great!

Javascript / jQuery Hide fields based on Selected Drop Down item

I have some code that I have created for an OnChange event which works perfectly.
<script type="text/javascript">
function UpdEventChanged(selectEl) {
var text = selectEl.options[selectEl.selectedIndex].text;
if (text == "Sickness" || text == "Holiday") {
$("input[id$=eventPostCode").hide();
$("#ContentPlaceHolder1_LBLUpdPCReq").hide();
$("#ContentPlaceHolder1_lblUpdPC").hide();
}
else {
$("input[id$=eventPostCode").show();
$("#ContentPlaceHolder1_LBLUpdPCReq").show();
$("#ContentPlaceHolder1_lblUpdPC").show();
}
}
</script>
I need to integrate the above code to make it work on the Page Load event. Here is my code:
// update Dialog
$('#updatedialog').dialog({
autoOpen: false,
width: 500,
buttons: {
"update": function() {
//alert(currentUpdateEvent.title);
var eventToUpdate = {
id: currentUpdateEvent.id,
//title: $("#eventName").val(),
title: $("#EventSalesPerson option:selected").text(),
description: $("#eventDesc").val(),
salesperson: $("#EventSalesPerson option:selected").text(),
eventPostCode: $("input[id$=eventPostCode]").val(),
eventname: $("#EventEventName option:selected").text()
};
{
PageMethods.UpdateEvent(eventToUpdate, updateSuccess);
$(this).dialog("close");
currentUpdateEvent.title = $("#eventName").val();
currentUpdateEvent.description = $("#eventDesc").val();
currentUpdateEvent.salesperson = $("#EventSalesPerson option:selected").text();
currentUpdateEvent.eventname = $("#EventEventName option:selected").text();
currentUpdateEvent.eventPostCode = $("input[id$=eventPostCode]").val();
$('#calendar').fullCalendar('updateEvent', currentUpdateEvent);
location.reload(true);
}
},
"delete": function() {
if (confirm("do you really want to delete this event?")) {
PageMethods.deleteEvent($("#eventId").val(), deleteSuccess);
$(this).dialog("close");
$('#calendar').fullCalendar('removeEvents', $("#eventId").val());
}
}
}
});
If #EventEventName selected text = Holiday or Sickness then I need the following items to be hidden:
"input[id$=eventPostCode"
"#ContentPlaceHolder1_LBLUpdPCReq"
"#ContentPlaceHolder1_lblUpdPC"
And obviously if they are not selected then the above should be displayed.
Thanks
It looks like you need something about like this:
var EventEventNameText = $('#EventEventName').val();
if (EventEventNameText=='Holiday' || EventEventNameText=='Sickness') {
$('#eventPostCode').hide();
$('#ContentPlaceHolder1_LBLUpdPCReq').hide();
$('#ContentPlaceHolder1_lblUpdPC').hide();
}
Let me know how that works for you.

Profiling jQuery, how do I make my app more snappy?

I have some calls to jQuery functions like 14,000 times... what the hell? I don't have that many functions, really just simple stuff like appending and removing DOM elements, why do some of my event handlers call functions so many times?
Plus to compound my issues, Firebug's profiler just show's the min'd functions names... and even when I use the uncompressed library it mostly just shows init() or $.()
Does anyone have any tricks?
So I know this is a lot, but it seems really inefficient, it executes on our page newgoldleaf.com, some of the functions take almost 50ms to run... is that a long time or is it just me?
// prepare ajax for form posts
jQuery.ajaxSetup({
"beforeSend" : function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
// initializes panels and gets url hash, shows correct panel
jQuery.fn.initPanes = function() {
$("div#main_content > div:not(.message)").addClass("inactive");
var hash = window.location.hash.substr(1);
this.each(function () {
if ($(this).hasClass(hash)) {
var panelToShow = "." + $(this).attr("class");
$(panelToShow).removeClass("inactive").toggleClass("active");
}
});
// if no hash found in url, activate first menu item
if (hash == "" ) {
$(this).eq(0).activatePane();
}
};
// shows panel when user clicks sidebar links
jQuery.fn.activatePane = function(pane) {
if ($(this).hasClass("unavailable") == true) {
return false;
}
if ($(this).hasClass("active") == false) {
$("div#main_content > div:not(.message)").hide().removeClass("active").addClass("inactive");
$(this).siblings().removeClass("active");
var panelToShow = "div#main_content div." + $(this).attr("class");
// set the hash in the url
window.location.hash = $(this).attr("class");
$(this).toggleClass("active");
$(panelToShow).fadeIn("slow").removeClass("inactive").addClass("active");
};
};
jQuery.fn.functionName = function() {
};
$(document).ready(function (){
$('ul.examples li:not(img, h5, a)').hover(function (){
var bubble = $(this).find("h5.bubble")
bubble.animate({
opacity:".99",
bottom:"28px"
}, 200);
}, function (){
var bubble = $(this).find("h5.bubble")
bubble.animate({
opacity:"0",
bottom:"38px"
}, 200).animate({
bottom:"20px"
}, 0);
});
// hide/show comment form for users with javascript
$("div#comments_not_allowed").hide();
$("form#new_comment").show();
// $("body#index div.preview").slideShow();
// error and flash notice animation
$(".message").animate({
opacity: "1",
}, 2000).animate({
opacity: "0",
}, 2000).hide(500);
// home page caption bubble for blog image fade in
$("body#index h5.bubble").fadeIn("slow");
$("body#index h5.bubble").animate({
bottom: "22px",
opacity: ".99"
}, 1000);
$("form#new_comment").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), null, "script");
return false;
});
$("form#new_lead").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), null, "script");
return false;
});
if ($("ul.panels").length > 0 ) {
// panel animation
$("div#aside ul li").initPanes();
$("div#aside ul li").css({
cursor:"pointer"
});
$("div#aside ul li").click(function () {
$(this).activatePane();
});
};
$(document).load(function() {
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
function startAnalytics() {
var pageTracker = _gat._getTracker("UA-7434953-1");
pageTracker._initData();
pageTracker._trackPageview();
}
if (window.addEventListener) {
window.addEventListener('load', startAnalytics, false);
}
else if (window.attachEvent) {
window.attachEvent('onload', startAnalytics);
}
})
})

Categories

Resources