Using jquery with OO Javascript - javascript

I'm trying to çreate a jquery popup script OO style. I'm doing this because I would like to expand this code with more jquery/javascript without losing oversight. The errors I'm receiving are Object #<HTMLDivElement> has no method 'centerPopup' and Resource interpreted as Script but transferred with MIME type text/x-c: I'm new to OO javascript, but have quite the experience in OO PHP
function popup(){
var popupStatus = 0;
$(document).ready(function () {
$("#button").click(function()
{
this.centerPopup();
this.loadPopup();
});
$("#backgroundPopup").click(function()
{
this.disablePopup();
});
$(document).keypress(function(e)
{
if(e.keyCode==27 && popupStatus==1)
{
this.disablePopup();
}
});
});
this.loadPopup = function (){
if(this.popupStatus==0)
{
$("#backgroundPopup").css(
{
"opacity": "0.7"
});
$("#backgroundPopup").fadeIn("slow");
$("#popupContact").fadeIn("slow");
this.popupStatus = 1;
}
}
this.disablePopup = function (){
if(this.popupStatus==1)
{
$("#backgroundPopup").fadeOut("slow");
$("#popupContact").fadeOut("slow");
this.popupStatus = 0;
}
}
this.centerPopup = function (){
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupContact").height();
var popupWidth = $("#popupContact").width();
$("#popupContact").css(
{
"position": "absolute",
"top": windowHeight/2-popupHeight/2,
"left": windowWidth/2-popupWidth/2
});
$("#backgroundPopup").css(
{
"height": windowHeight
});
}
}
var popup = new popup()
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="css/popup.css" type="text/css" media="screen" />
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="js/popup2.js" type="text/javascript"></script>
</head>
<body>
<center>
<div id="button"><input type="submit" value="Popup!" /></div>
</center>
<div id="popupContact">
<a id="popupContactClose">x</a>
</div>
<div id="backgroundPopup"></div>
</body>
</html>

$("#button").click(function()
{
this.centerPopup();
this.loadPopup();
});
this isn't what you actually think. It's not the instance of popup, but the DOM element (#button). You can fix this by saving a reference on your instance at the beginning of your class:
function popup(){
var self = this;
this.popupStatus = 0; // you should use `this` here
$(document).ready(function () {
$("#button").click(function()
{
self.centerPopup();
self.loadPopup();
});
/* ... snip ... */

Related

Remember place scrolling on each page using jquery

I have 3 files besides the main HTML: test.html, test2.html and test3.html.
When you press one of the buttons a page is loaded. So I want the scroll position to be saved between page loads. Example: you load page test and then scroll to the middle, load page test2, scroll to the end, load back page test and it should be in the middle.
How could I archive this ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery load() Demo</title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#button1").click(function() {
$("#box").load("test.html");
});
$("#button2").click(function() {
$("#box").load("test2.html");
});
$("#button3").click(function() {
$("#box").load("test3.html");
});
});
</script>
</head>
<body>
<div style="position: fixed;"><button id="button1">test</button> <button id="button2">test2</button> <button id="button3">test3</button> </div>
<br><br>
<div id="box">
<h2>Click button to load new content inside DIV box</h2>
</div>
</body>
</html>
This is onde of many ways to do what you want
function currPos() { // crossbrowser get actual scroll position
return window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
}
function loadAndSavePosition(button) {
var pos = currPos(); // obtain current position
if (page) // if there is a loaded page, save the position of the actual page
scrollData[page] = pos;
page = button.target.innerText;
// simulates page load
h2.innerHTML = (button.target.innerText + ' ').repeat(10000);
if (scrollData[page]) { //if there is an already save value ...
window.scrollTo(0, scrollData[page]); // ...move to that position...
} else { // ... or to the top if there isn't.
scrollData[page] = 0;
window.scrollTo(0, 0);
}
}
var h2 = document.getElementById('h2');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button3 = document.getElementById('button3');
var page = ''; // loaded page
var scrollData = {}; // object for saving the page scroll positions
// associate onclick event to the loadAndSavePosition function
[].slice.call(document.getElementsByTagName('button')).forEach(
button => button.onclick = loadAndSavePosition);
<div style="position: fixed;">
<button id="button1">test</button>
<button id="button2">test2</button>
<button id="button3">test3</button>
</div>
<br>
<br>
<div id="box">
<h2 id='h2'>Click button to load new content inside DIV box</h2>
</div>
JSFiddle: https://jsfiddle.net/s5dkL5nn/7/
To remember scroll of all pages use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
here's what you need to do, if I understand your problem correctly:
you re gonna save the current position of the page in a variable before loading new one. And set scroll position to the value you saved when you call that page again.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery load() Demo</title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var pos = {}
var lastLoaded
$('.btn').click(function(e) {
v = e.target.value
pos[lastLoaded] = $('body').scrollTop()
$("#box").load(v);
lastLoaded = v
if(pos[v])
$('body').scrollTop(pos[v])
else
$('body').scrollTop(0)
})
});
</script>
</head>
<body>
<div style="position: fixed;">
<button class="btn" id="button1" value="test1.html">test</button>
<button class="btn" id="button2" value="test2.html">test2</button>
<button class="btn" id="button3" value="test3.html">test3</button>
</div>
<br><br>
<div id="box">
<h2>Click button to load new content inside DIV box</h2>
</div>
</body>
</html>

Implemeting Create and Delete function properly using javascript

I am able to create a div using javascript. However, not able to remove that div that I created previously. Only after post-back, I can remove that div. Actually after creating div, script cannot find that div because page did not loaded again.
What I want to do is to create a page that I am able to add an item and remove that item.
Add script works fine.
Remover script:
<script type="text/javascript">
$(function () {
$('.remove ,.shop-button-large, .shop-button-add').click(function () {
var itemToDelete = $(this).attr("data-id");
if (itemToDelete != '') {
$.post("/ShoppingBox/RemoveFromBox", { "id": itemToDelete },
function (data) {
$("#boxItem-" + itemToDelete + "-" + data.ItemCount).fadeOut(300);
});
}
});
});
</script>
The click handler for the remove was done before the DOM node was rendered. It needs to be insider the $(function() { ... }
http://plnkr.co/edit/IhtyH6ampodXICPBv6Fq?p=preview
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(function() {
$("#create").click(function() {
var createDiv = document.createElement("div");
createDiv.id = "myDiv";
createDiv.style.margin = "0 auto";
createDiv.style.width = "600px";
createDiv.style.height = "600px";
createDiv.style.backgroundColor = "red";
document.getElementById("myBody").appendChild(createDiv);
});
$("#remove").click(function() {
console.log('remove', $("#myDiv"));
$("#myDiv").fadeOut(300);
});
});
</script>
</head>
<body id="myBody">
Create
Remove
</body>
</html>
In order to clarify, I have prepared a simple code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="js/jquery-2.1.3.intellisense.js"></script>
<script src="js/jquery-2.1.3.min.js"></script>
<script src="js/jquery-2.1.3.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(function () {
$("#create").click(function () {
var createDiv = document.createElement("div");
createDiv.id ="myDiv";
createDiv.style.margin = "0 auto";
createDiv.style.width = "600px";
createDiv.style.height = "600px";
createDiv.style.backgroundColor = "red";
document.getElementById("myBody").appendChild(createDiv);
});
});
$("#remove").click(function () {
$("#myDiv").fadeOut(300);
});
</script>
<title></title>
</head>
<body id="myBody">
Create
Remove
</body>
</html>

How to debug a jQuery / JavaScript conflict?

I have two WebUsercontrols(.ascx) in my aspx page. One is for slide show and another one is for FullCalendar. Both are working fine while running Separately, but when I run both User controls in same page script conflict error occurs, as follows:
Error description is:
Script are:
SlideShow.ascx
<script type="text/javascript" src="../Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
function pageLoad(sender, args) {
var $slides = $('.slide'),
slideWidth = $slides.width(),
numberOfSlides = $slides.length,
speed = 5000,
$holder = $slides.wrapAll('<div id="slidesHolder"></div>').css('float', 'left').parent().width(slideWidth * numberOfSlides);
setInterval(changePosition, speed);
function changePosition() {
$holder.animate({
'marginLeft': 0 - slideWidth
}, function () {
$holder.css('marginLeft', 0).children().first().appendTo($holder);
});
}
}
</script>
FullCalendar.ascx
<script src="http://code.jquery.com/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../Scripts/jquery-ui-1.7.3.custom.min.js" type="text/javascript"></script>
<script src="../Styles/fullcalendar.min.js" type="text/javascript"></script>
<script src="../Scripts/calendarscript.js" type="text/javascript"></script>
I have tried for noConflict. If i use noConflict one of the script is not working.
Try to Run after removing this : ../Scripts/jquery-1.4.1.js
If it is working then ok else
Try to put this at the bottom of your page
<script type="text/javascript">
function pageLoad(sender, args) {
var $slides = $('.slide'),
slideWidth = $slides.width(),
numberOfSlides = $slides.length,
speed = 5000,
$holder = $slides.wrapAll('<div id="slidesHolder"></div>').css('float', 'left').parent().width(slideWidth * numberOfSlides);
setInterval(changePosition, speed);
function changePosition() {
$holder.animate({
'marginLeft': 0 - slideWidth
}, function () {
$holder.css('marginLeft', 0).children().first().appendTo($holder);
});
}
}
</script>
use <script>jQuery.noConflict();</script> and replace the word jquery from $
<script type="text/javascript" src="../Scripts/jquery-1.4.1.js"></script>
After including jQuery, you should call $.noConflict(). This will remove the "$" from the global namespace:
<script language="javascript">
var $j = jQuery.noConflict();
</script>
At this point, you should use $j instead of $ if you want to call jQuery code. Or you could use a trick by wrapping the $ symbol in a closure
<script type="text/javascript">
function pageLoad(sender, args) {
var $jslides = $j('.slide'),
slideWidth = $jslides.width(),
numberOfSlides = $jslides.length,
speed = 5000,
$jholder = $jslides.wrapAll('<div id="slidesHolder"></div>').css('float', 'left').parent().width(slideWidth * numberOfSlides);
setInterval(changePosition, speed);
function changePosition() {
$jholder.animate({
'marginLeft': 0 - slideWidth
}, function () {
$jholder.css('marginLeft', 0).children().first().appendTo($jholder);
});
}
}
</script>
Hope this helps..!!
Happy Coding :)

Print content of jquery dialog to a printer

I have the following jQueryUI dialog. How can I print the content of the dialog? The content could be any HTML such as a table, image, etc. There were several earlier answers to this question,however, they appear to be out of date.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(function() {
$("#openDialog").click(function(){$("#myDialog").dialog('open')});
$( "#myDialog" ).dialog({
modal: true,
autoOpen : false,
buttons: {Ok: function() {alert('print');}}
});
});
</script>
</head>
<body>
<button id="openDialog">Click</button>
<div id="myDialog" title="My Dialog">
<p>Print this text!</p>
<img alt="And print this image" src="myImg.png">
</div>
</body>
</html>
I developed my own plugin with code is below, and a live example is located at http://jsfiddle.net/fyu4P/embedded/result/.
On FF 26.0, it works, however, after printing a couple of times, FF asks the user if popups should be disabled which I wish not to happen. Also, it doesn't work with older IE, and likely other browsers. Don't worry, when printing, you still need to click the operating system print dialog, so you won't waste any paper! I've asked https://codereview.stackexchange.com/questions/39235/critique-of-jquery-plugin-which-will-print-to-a-printer-an-element-or-a-jqueryui for any recommendations.
Actual Plugin:
/*
* jQuery printIt
* Print's the selected elements to the printer
* Copyright Michael Reed, 2014
* Dual licensed under the MIT and GPL licenses.
*/
(function($){
var defaults = {
elems :null, //Element to print HTML
copy_css :false,//Copy CSS from original element
external_css :null //New external css file to apply
};
var methods = {
init : function (options) {
var settings = $.extend({}, defaults, options)
elems=$(settings.elems);
return this.each(function () {
$(this).click(function(e) {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).load(function(){
elems.each(function(){
iframe.contentWindow.document.body.appendChild(this.cloneNode(true));
});
if(settings.copy_css) {
var arrStyleSheets = document.getElementsByTagName("link");
for (var i = 0; i < arrStyleSheets.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyleSheets[i].cloneNode(true));
}
var arrStyle = document.getElementsByTagName("style");
for (var i = 0; i < arrStyle.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyle[i].cloneNode(true));
}
}
if(settings.external_css) {
var style = document.createElement("link")
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = settings.external_css;
iframe.contentWindow.document.head.appendChild(style);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = 'window.print();';
iframe.contentWindow.document.head.appendChild(script);
$(iframe).hide();
});
});
});
},
destroy : function () {
//Anything else I should do here?
delete settings;
return this.each(function () {});
}
};
$.fn.printIt = 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.printIt');
}
};
}(jQuery)
);
To configure:
$(function () {
$("#openDialog").click(function () {
$("#myDialog").dialog('open')
});
$("#myDialog").dialog({
modal: true,
autoOpen: false
});
$('#printIt').printIt({
elems: $("#myDialog"),
copy_css: true,
external_css: 'test2.css'
});
});
This will add a printable area, and puts modal html into it.
$(function () {
$("#openDialog").click(function () {
$("#myDialog").dialog('open')
});
$("#myDialog").dialog({
modal: true,
autoOpen: false,
buttons: {
Ok: function (e) {
$('#divToPrint').html($(this)[0].innerHTML).printArea();
}
}
});
});
You need to create a new <div id="divToPrint"></div> if you want to not display the new div, just use style="display: none;"
Then when you press CTRL+P it will print what you created...
Try like below.....and call your div id. You should be good to go.
buttons: {
"Print": function() {
$("#dialog").printArea();
},
"Close": function() {
$(this).dialog("close");
}
}

touchenter event not being called

Can anyone tell me why the touchenter event is not working in this code. The mouseenter works fine on a desktop. Should be so simple, I'm missing something though.
Example here - http://jsfiddle.net/gCEqH/6/
Full code below:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<img id="myImg" src="http://jackiehutchings.com/wp-content/uploads/2011/09/g-plus-icon-96x96.png" />
<script>
$(window).load(function() {
$('#myImg').on("touchenter mouseenter", function(event){
alert('entered!');
});
});
</script>
</body>
</html>
Maybe something like this would work?
var elementIdTouching = "";
$('body').on("touchmove", function(e){
var tList = e.touches; // get list of all touches
for (var i = 0; i < tList.length; i++) {
var thisTouch = tList[i]; // not 100% sure about this
var elementTouching = document.elementFromPoint(
thisTouch.screenX,
thisTouch.screenY
);
if (elementTouching.id != elementIdTouching) {
elementIdTouching = elementTouching.id;
if (elementTouching.id == "myImg") {
alert("entered!");
}
}
}
}).on("touchend", function(e){
elementIdTouching = "";
});
$('#myImg').on("mouseenter", function(e){
alert('entered!');
});
tList ~ https://developer.mozilla.org/en-US/docs/Web/API/TouchList
Disclaimer: I haven't tested this.

Categories

Resources