Javascript Calling object methods within same object not working well - javascript

In This theme object i have created 2 properties.
I placed this.changeThemeTo(1); under the Event Listener, after that it worked. But i want to place it within if tag
But seems giving an error when put it within if
Uncaught TypeError: this.changeThemeTo is not a function
please help to fix this. Thanks..
var theme = {
changeThemeTo: function (theme_value) {
sessionStorage.removeItem('THEME'); // remove old theme from session storage
if (theme_value == 0) {
sessionStorage.setItem("THEME", 'dark');
} else if (theme_value == 1) {
sessionStorage.setItem("THEME", 'light');
}
document.body.className = sessionStorage.getItem("THEME");
},
init: function () {
document.body.classList.add("fade");
setTimeout(function () {
document.body.classList.remove("fade");
}, 100);
var themes = ['dark', 'light'];
themes.forEach(function (item) {
var button = document.querySelector("." + item);
if (button) {
button.addEventListener("click", function () {
if (item == "dark") {
this.changeThemeTo(0);
} else if (item == "light") {
this.changeThemeTo(1);
}
});
}
}, this);
}
}
window.onload = function () {
theme.init();
}
Here my html code
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.dark {
background-color: #191919;
color: #EEEEEE;
}
.light {
background-color: #EEEEEE;
color: #191919;
}
</style>
</head>
<body>
<div id="change-theme">
DARK
LIGHT
</div>
</body>
</html>

use self.changeThemeTo instead this.changeThemeTo. and define self = this as per the below code sample. also optimized some portion of the code.
var theme = {
changeThemeTo: function (theme_value) {
sessionStorage.setItem("THEME", theme_value);
document.body.className = theme_value;
},
init: function () {
document.body.classList.add("fade");
setTimeout(function () {
document.body.classList.remove("fade");
}, 100);
var themes = ['dark', 'light'];
var self = this;
themes.forEach(function (item) {
var button = document.querySelector("." + item);
if (button) {
button.addEventListener("click", function () {
self.changeThemeTo(item);
});
}
}, this);
}
}
window.onload = function () {
theme.init();
}
<style type="text/css">
.dark {
background-color: #191919;
color: #EEEEEE;
}
.light {
background-color: #EEEEEE;
color: #191919;
}
</style>
<div id="change-theme">
DARK
LIGHT
</div>

Related

trying to toggle stylesheet using button

I am attempting to switch stylesheets on my website using a button.
When I use this code, the stylesheet becomes nonexistent when I press the button and I cannot switch back unless I refresh the site. I do not know what is happening.
JavaScript
const stylesUrls = ["C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\claires.css", "C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\queen-of-hearts.css"];
window.onload = function(){
let switcherBtn = document.getElementById("themes");
switcherBtn.onclick = function() {
let style = document.getElementById('ss');
let stylesUrl = stylesUrls.shift();
style.href = stylesUrl;
stylesUrls.push(stylesUrl);
}
};
HTML
<link rel="stylesheet" href='C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\claires.css' id="ss" type="text/css">
<button id="themes" type="button">Switch Theme</button>
Store the current index in a variable and change that instead.
const stylesUrls = ["foo", "bar"];
window.onload = function() {
const switcherBtn = document.getElementById("themes");
let currentIndex = 0;
switcherBtn.addEventListener("click", function() {
let style = document.getElementById('ss');
let stylesUrl = stylesUrls[currentIndex];
style.href = stylesUrl;
if (currentIndex === 0) {
currentIndex = 1;
} else {
currentIndex = 0;
}
});
}
If you're trying to do themes, you can change a class on the root html tag and include a style tag to both stylesheets and then use the corresponding class in each stylesheet.
Example
queen-of-hearts.css;
html.queen h1 {
color: red;
font-size: 20px;
}
html.queen div {
background-color: pink;
}
claires.css;
html.claire h1 {
color: blue;
font-size: 30px;
}
html.claire div {
background-color: green;
}
HTML;
<html class="queen"> <!-- Toggle between queen and claire using JavaScript -->
<head>
<link href="insert link to claires.css here" />
<link href="insert link to queen-of-hearts.css here" />
</head>
</html>
JS;
...
switcherBtn.addEventListener("click", function() {
if (document.documentElement.classList.contains("claire")) {
document.documentElement.classList.replace("claire", "queen");
} else {
document.documentElement.classList.replace("queen", "claire");
}
});
Demo

Adding a New Click Handler To An Existing Element?

I'm trying to add a new click handler to the #myDiv element below. I've tried something like this:
document.getElementById("myDiv").addEventListener("click", blah);
function blah() {
console.log("test");
}
But I keep getting a console error stating, "Cannot read properties of null (reading 'addEventListener'). Is this because the other event listener isn't being called yet? Any help would be greatly appreciated. Thanks!
<!DOCTYPE html>
<html lang="en">
<head>
<style>
[data-color="red"] { color: red; }
[data-color="blue"] { color: blue; }
[data-color="green"] { color: green; }
[data-color="orange"] { color: orange; }
[data-color="purple"] { color: purple; }
</style>
<script>
window.myHandler = function () {
console.log('Click!');
};
window.getRandomNumber = function (max) {
return Math.floor(Math.random() * max)
}
var colors = ['red', 'blue', 'green', 'orange', 'purple'];
window.changeHeadlineColor = function (croHeadline) {
var random = getRandomNumber(5000);
var randomString = random.toString();
setTimeout(() => {
var colorKey = (randomString.length < 4) ? 0 : parseInt(randomString.charAt(0));
croHeadline.setAttribute('data-color', colors[colorKey]);
changeHeadlineColor(croHeadline);
}, random);
};
</script>
<script>
////////////////////
/* YOUR CODE HERE */
////////////////////
</script>
</head>
<body>
<div id="myDiv">OMG Click me!</div>
<script>
document.querySelector('#myDiv').addEventListener('click', myHandler);
setTimeout(() => {
myDiv.insertAdjacentHTML('beforebegin', '<h1 id="cro-headline" data-color="red">Cro Metrics</h1>');
var croHeadline = document.querySelector('#cro-headline');
changeHeadlineColor(croHeadline);
}, getRandomNumber(5000));
</script>
</body>
</html>
Because document.getElementById("myDiv") is in the head tag which execute before the DOM loaded.
One solution is to add it in a script at the end of the body ( after the DOM loaded )
The second solution to make your script as module.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
[data-color="red"] { color: red; }
[data-color="blue"] { color: blue; }
[data-color="green"] { color: green; }
[data-color="orange"] { color: orange; }
[data-color="purple"] { color: purple; }
</style>
<script>
window.myHandler = function () {
console.log('Click!');
};
window.getRandomNumber = function (max) {
return Math.floor(Math.random() * max)
}
var colors = ['red', 'blue', 'green', 'orange', 'purple'];
window.changeHeadlineColor = function (croHeadline) {
var random = getRandomNumber(5000);
var randomString = random.toString();
setTimeout(() => {
var colorKey = (randomString.length < 4) ? 0 : parseInt(randomString.charAt(0));
croHeadline.setAttribute('data-color', colors[colorKey]);
changeHeadlineColor(croHeadline);
}, random);
};
</script>
<script type="module">
window.blah = function () {
console.log('Click!');
};
document.querySelector('#myDiv').addEventListener('click', blah);
</script>
</head>
<body>
<div id="myDiv">OMG Click me!</div>
<script>
document.querySelector('#myDiv').addEventListener('click', myHandler);
setTimeout(() => {
myDiv.insertAdjacentHTML('beforebegin', '<h1 id="cro-headline" data-color="red">Cro Metrics</h1>');
var croHeadline = document.querySelector('#cro-headline');
changeHeadlineColor(croHeadline);
}, getRandomNumber(5000));
</script>
</body>
</html>

How can I customize an interface and save it so it can be accessed again?

I am experimenting with Javascript drag and drop. I have built a simple interface editable with drag and drop features.
Here my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Drag&Drop</title>
</head>
<body>
<div class="empty">
<div class="item" draggable="true"></div>
</div>
<div class="empty"></div>
<div class="empty"></div>
<div class="empty"></div>
<div class="empty"></div>
<script src="js/main.js"></script>
</body>
</html>
Here my style.css
body {
background: white;
}
.lists {
display: flex;
flex:1;
width 100%;
overflow-x:scroll;
}
.item {
background-image: url('http://source.unsplash.com/random/150x150');
position: relative;
height: 150px;
width: 150px;
top: 5px;
left: 5px;
cursor: pointer;
}
.empty {
display: inline-block;
height: 160px;
width: 160px;
margin: 5px;
border: 3px blue;
background-color: lightgray;
}
.hold {
border: solid lightgray 4px;
}
.hovered {
background: darkgray;
border-style: dashed;
}
.invisible {
display: none;
}
Here my main.js:
const item = document.querySelector('.item');
const empties = document.querySelectorAll('.empty');
//Item Listeners
item.addEventListener('dragstart',dragStart);
item.addEventListener('dragend',dragEnd);
//Loop through empties
for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
//Drag Functions
function dragStart() {
console.log('Start');
this.className += ' hold';
setTimeout(()=> this.className = 'invisible', 0);
}
function dragEnd() {
console.log('End');
this.className = 'item';
}
function dragOver(e) {
console.log('Over');
e.preventDefault();
}
function dragEnter(e) {
console.log('Enter');
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
console.log('Leave');
this.className = 'empty';
}
function dragDrop() {
console.log('Drop');
this.className = 'empty';
this.append(item)
}
Ok. Let's imagine that I am a user who moved the picture from the first box to the fourth box. When I login the next time, I am expecting to see the picture on the fourth box.
The questions are:
how do I save the new user's layout?
how do I recall it when I open the page again?
I am not interested in the "backend" part. I just want to understand how to extract info from a custom layout built with Javascript and how to rebuild it on a new page.
Many thanks!
What you can do is save the index in the list of "empty" class elements in local storage. Check out the new JS code:
const empties = document.querySelectorAll('.empty');
let storage = JSON.parse(localStorage.getItem("elementLocation")).location
let storeData = {location: storage}
if (storage !== null) {
let array = document.getElementsByClassName("empty");
array[0].innerHTML = "";
array[storage].innerHTML = '<div class="item" draggable="true">'
alert(storage)
}
const item = document.querySelector('.item');
//Item Listeners
item.addEventListener('dragstart',dragStart);
item.addEventListener('dragend',dragEnd);
//Loop through empties
for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
//Drag Functions
function dragStart() {
this.className += ' hold';
setTimeout(()=> this.className = 'invisible', 0);
}
function dragEnd() {
this.className = 'item';
}
function dragOver(e) {
e.preventDefault();
}
function dragEnter(e) {
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
this.className = 'empty';
}
function dragDrop() {
this.className = 'empty';
this.append(item);
let parentArray = document.getElementsByClassName("empty");
storeData.location = [].indexOf.call(parentArray, this);
localStorage.removeItem('elementLocation');
localStorage.setItem('elementLocation', JSON.stringify(storeData));
alert(JSON.parse(localStorage.getItem("elementLocation")).location);
}
Here's the JSFiddle: https://codepen.io/mero789/pen/eYpvYVY
This is the new main.js thanks to Ameer input
const empties = document.querySelectorAll('.empty');
let storage = JSON.parse(localStorage.getItem("elementLocation"))
let storeData = {location: storage}
if (storage == null) {
console.log("Storage Non Existing")
}
else {
console.log("Storage Existing")
console.log(storage.location)
let array = document.getElementsByClassName("empty");
array[0].innerHTML = "";
array[storage.location].innerHTML = '<div class="item" draggable="true">'
alert(storage.location)
}
const item = document.querySelector('.item');
//Item Listeners
item.addEventListener('dragstart',dragStart);
item.addEventListener('dragend',dragEnd);
//Loop through empties
for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
//Drag Functions
function dragStart() {
this.className += ' hold';
setTimeout(()=> this.className = 'invisible', 0);
}
function dragEnd() {
this.className = 'item';
}
function dragOver(e) {
e.preventDefault();
}
function dragEnter(e) {
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
this.className = 'empty';
}
function dragDrop() {
this.className = 'empty';
this.append(item);
let parentArray = document.getElementsByClassName("empty");
storeData.location = [].indexOf.call(parentArray, this);
localStorage.removeItem('elementLocation');
localStorage.setItem('elementLocation', JSON.stringify(storeData));
alert(JSON.parse(localStorage.getItem("elementLocation")).location);
}

Drag and drop picture to text and with double click to remove the text inside the box

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<title>Basic Drag and Drop</title>
<style>
#drop {
min-height: 200px;
width: 200px;
border: 3px dashed #ccc;
margin: 10px;
padding: 10px;
clear: left;
}
p {
margin: 10px 0;
}
#triangle {
background: url(images/triangle.jpg) no-repeat;
}
#square {
background: url(images/square.gif) no-repeat;
}
#circle {
background: url(images/circle.jpg) no-repeat;
}
#red {
background: url(images/red.jpg) no-repeat;
}
#yellow {
background: url(images/yellow.jpg) no-repeat;
}
#green {
background: url(images/green.jpg) no-repeat;
}
.drag {
height: 48px;
width: 48px;
float: left;
-khtml-user-drag: element;
margin: 10px;
}
</style>
<script>
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();
(function () {
var pre = document.createElement('pre');
pre.id = "view-source"
// private scope to avoid conflicts with demos
addEvent(window, 'click', function (event) {
if (event.target.hash == '#view-source') {
// event.preventDefault();
if (!document.getElementById('view-source')) {
// pre.innerHTML = ('<!DOCTYPE html>\n<html>\n' + document.documentElement.innerHTML + '\n</html>').replace(/[<>]/g, function (m) { return {'<':'<','>':'>'}[m]});
var xhr = new XMLHttpRequest();
// original source - rather than rendered source
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
pre.innerHTML = this.responseText.replace(/[<>]/g, function (m) { return {'<':'<','>':'>'}[m]});
prettyPrint();
}
};
document.body.appendChild(pre);
// really need to be sync? - I like to think so
xhr.open("GET", window.location, true);
xhr.send();
}
document.body.className = 'view-source';
var sourceTimer = setInterval(function () {
if (window.location.hash != '#view-source') {
clearInterval(sourceTimer);
document.body.className = '';
}
}, 200);
}
});
})();
</script>
<style id="jsbin-css">
</style>
</head>
<body>
<div class="drag" id="triangle" draggable="true"></div>
<div class="drag" id="square" draggable="true"></div>
<div class="drag" id="circle" draggable="true"></div>
<div class="drag" id="red" draggable="true"></div>
<div class="drag" id="yellow" draggable="true"></div>
<div class="drag" id="green" draggable="true"></div>
<div id="drop"></div>
<script>
function cancel(e) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
var dragItems = document.querySelectorAll('[draggable=true]');
for (var i = 0; i < dragItems.length; i++) {
addEvent(dragItems[i], 'dragstart', function (event) {
// store the ID of the element, and collect it on the drop later on
event.dataTransfer.setData('Text', this.id);
});
}
var drop = document.querySelector('#drop');
// Tells the browser that we *can* drop on this target
addEvent(drop, 'dragover', cancel);
addEvent(drop, 'dragenter', cancel);
addEvent(drop, 'drop', function (e) {
if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.
this.innerHTML += '<p>' + e.dataTransfer.getData('Text') + '</p>';
return false;
});
</script>
</body>
</html>
how to double click remove the text inside the textbox by using html5? I having problem on how to remove the text out from the textbox in this html5. things can be drag and drop inside, but i want to remove the things inside that i have been dragged inside... i having problem on removing the item inside that.
Try using this.
document.getElementById('selectID').ondblclick = function(){
alert(this.selectedIndex);//remove your text here
};

My jQuery callback is failing

I created a plug-in to display a Metro MessageBar and it works great. I was asked to support callbacks and added some code to the fadeIn functionality for this purpose.
For some reason, the callback shows as a valid function, but doesn't call?
HERE IS THE CONSOLE MESSAGE I AM GETTING:
this.trigger is not a function
...any help is appreciated.
THIS IS HOW TO USE THE PLUG-IN:
this.showSubmitMessage = function () {
var options = {
message: "This is a test.",
messageType: "information"
};
// self.btnSubmit.click IS a valid function!!! Use your own if you want.
nalco.es.rk.globals.messageBarManager.display(options, self.btnSubmit.click);
};
THIS IS THE OFFENDING AREA-OF-CODE IN THE PLUG-IN:
this.fadeIn = function (element, callback) {
element.prependTo(self.container).centerToScrollTop().fadeIn(self.globals.fadeDuration, function() {
if (callback != null)
if ($.isFunction(callback))
setTimeout(function () {
callback();
}, self.globals.callbackDuration);
});
};
THIS IS THE ENTIRE USER-CONTROL PLUG-IN:
Please notice the code for the file-dependency "jquery.Extensions.js" is at the bottom of this posting.
<script src="Scripts/jQuery/Core/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="Scripts/jQuery/Core/jquery.tmpl.js" type="text/javascript"></script>
<script src="Scripts/jQuery/jquery.Extensions.js" type="text/javascript"></script>
<style type="text/css">
.messageBar { background-color: #DDDDDD; color: #666666; display: none; left: 0; padding: 15px; position: absolute; top: 0; width: 932px; z-index: 1000; }
.messageBar .content { width: 100%; }
.messageBar .content td.image { width: 70px; }
.messageBar .content td.button { width: 60px; }
.messageBar .button { margin-top: 0px; }
.messageBar .content .icon { background-repeat: no-repeat; height: 31px; overflow: hidden; width: 31px; }
.messageBar .content .message { }
.messageBar .content .image { background-repeat: no-repeat; height: 10px; overflow: hidden; width: 70px; }
.messageBar.error { background-color: #FFBABA; color: #D8000C; }
.messageBar.information { background-color: #99CCFF; color: #00529B; }
.messageBar.success { background-color: #DFF2BF; color: #4F8A10; }
.messageBar.warning { background-color: #FEEFB3; color: #9F6000; }
.messageBar.error .content .icon { background-image: url('/_layouts/images/error.png'); }
.messageBar.information .content .icon { background-image: url('/_layouts/images/info.png'); }
.messageBar.success .content .icon { background-image: url('/_layouts/images/success.png'); }
.messageBar.warning .content .icon { background-image: url('/_layouts/images/warning.png'); }
</style>
<script id="template-messageBar" type="text/html">
<div class="messageBar">
<table class="content">
<tbody>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td class="button">
<input type="button" value="Close" class="button metroButton" />
</td>
</tr>
</tbody>
</table>
</div>
</script>
<script id="template-messageBar-icon" type="text/html">
<div class="icon">
</div>
</script>
<script id="template-messageBar-message" type="text/html">
<div class="message">
${Message}
</div>
</script>
<script id="template-messageBar-image" type="text/html">
<div class="image">
</div>
</script>
<script type="text/javascript">
;nalco.es.rk.source.MessageBarManager = (function ($) {
var publicInstances = {};
publicInstances.Controller = Controller;
function Controller(options) {
var self = this;
this.messageTypes = { error: "error", information: "information", normal: null, success: "success", warning: "warning" };
this.globals = {
callbackDuration: 2000,
fadeDuration: 700,
workingImageUrl: "url('/_layouts/images/Nalco.ES.SharePoint.UI/metro-ajax-loader-blue.gif')"
};
this.defaults = {
message: "",
messageType: self.messageTypes.normal,
showIcon: false,
showWorkingImage: false
};
this.container = $('body');
this.templateMessageBarId = '#template-messageBar';
this.templateMessageBarIconId = '#template-messageBar-icon';
this.templateMessageBarMessageId = '#template-messageBar-message';
this.templateMessageBarImageId = '#template-messageBar-image';
this.selectors = { content: '.content', closeButton: '.button', root: '.messageBar' };
this.initialize = function () {
self.display(options);
};
this.display = function (options, callback) {
var empty = {};
var settings = $.extend(empty, self.defaults, $.isPlainObject(options) ? options : empty);
if (settings.messageType != null)
if (settings.messageType.length == 0)
settings.messageType = self.messageTypes.normal;
if (settings.message.length == 0)
return;
var eleMessageBar = $(self.templateMessageBarId).tmpl(empty);
var eleContent = $(self.selectors.content, eleMessageBar);
var eleCellOne = $('td:eq(0)', eleContent);
var eleCellTwo = $('td:eq(1)', eleContent);
var eleCellThree = $('td:eq(2)', eleContent);
var eleMessage = $(self.templateMessageBarMessageId).tmpl({ Message: settings.message });
var btnClose = $(self.selectors.closeButton, eleMessageBar);
if (settings.messageType != self.messageTypes.normal) {
eleMessageBar.addClass(settings.messageType);
if (settings.showIcon) {
var eleIcon = $(self.templateMessageBarIconId).tmpl(empty);
eleCellOne.css('width', '31px');
eleIcon.appendTo(eleCellOne);
}
}
eleMessage.appendTo(eleCellTwo);
btnClose.click(function () {
eleMessageBar.fadeOut(self.globals.fadeDuration, function () {
eleMessageBar.remove();
});
});
if (settings.showWorkingImage) {
var eleImage = $(self.templateMessageBarImageId).tmpl(empty);
eleCellThree.addClass('image');
eleImage.css('background-image', self.globals.workingImageUrl);
eleImage.appendTo(eleCellThree);
}
var elePreviousMessage = $(self.selectors.root, self.container);
if (elePreviousMessage.length > 0) {
btnClose = $(self.selectors.closeButton, elePreviousMessage);
btnClose.click();
setTimeout(function () { self.fadeIn(eleMessageBar, callback); }, self.globals.fadeDuration);
}
else
self.fadeIn(eleMessageBar, callback);
};
this.fadeIn = function (element, callback) {
element.prependTo(self.container).centerToScrollTop().fadeIn(self.globals.fadeDuration, function() {
if (callback != null)
if ($.isFunction(callback))
setTimeout(function () {
callback();
}, self.globals.callbackDuration);
});
};
self.initialize();
};
return publicInstances;
})(jQuery);
function initializeMessageBarManager() {
nalco.es.rk.globals.messageBarManager = new nalco.es.rk.source.MessageBarManager.Controller();
}
$(document).ready(function () {
initializeMessageBarManager();
if (typeof (Sys) != "undefined")
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initializeMessageBarManager);
});
</script>
THIS IS THE EXTENSIONS DEPENDENCY LISTED IN THE FILES ABOVE:
// **********************
// .centerToScrollTop
// Use -
// Centers an ELEMENT to the window's scrollTop.
//
// Example -
// $('.myElement').centerToScrollTop();
// **********************
(function ($) {
$.fn.extend({
centerToScrollTop: function (options) {
return this.each(function () {
var element = $(this);
var container = $(window);
var scrollTop = container.scrollTop();
var buffer = 30;
var top = scrollTop + buffer;
var left = (container.width() - element.outerWidth()) / 2 + container.scrollLeft();
element.css({ 'position': 'absolute', 'top': top, 'left': left });
return element;
});
}
});
})(jQuery);
This type of error occurs usually if you forgot to include some files like jquery-ui.min.js etc. Check carefully if you add all the necessary references.

Categories