Transfer pop up HTML content inside JS file - javascript

I have this working pop up HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<title>PopUp</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.popup.min.js"></script>
<script type="text/javascript">
jQuery(function () {
jQuery().popup();
});
</script>
</head>
<body>
Show popup
<div id="popup-box">
This is the pop up content. The quick brown fox jumps over the lazy dog.
</div>
</body>
</html>
The actual pop up content is inside the:
<div id="popup-box">
</div>
Is it possible to transfer the pop up HTML content (..) to my JS file? Actually inside the jQuery function click event? Example:
jQuery( document ).ready( function($) {
$('#triggerforpopup').live('click',(function() {
//launch the pop code to HTML
}));
});
So after the click event, the JS will simply pop it out, but it's originating inside the JS file not an HTML hidden on an existing content.
The reason is that I'm writing a Wordpress plugin and it would be convenient to have all this information in a JS file. I don't want putting additional HTML code in the existing template content which is hidden by default.
Thanks for helping.
UPDATE: I have created a fiddle for this one here: http://jsfiddle.net/codex_meridian/56ZpD/3/
(function (a) {
a.fn.popup = function (b) {
var c, d = [self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop];
a("body").append(c = a('<div id="popup-overlay"></div>')), _init = function () {
_add_overlay(), _add_buttons(), a("#popup-box #popup-content").css("max-height", a(window).height() - 400), a(window).on("resize", function () {
a("#popup-box #popup-content").css("max-height", a(window).height() - 400)
})
}, _add_overlay = function () {
c.css({
opacity: .85,
position: "absolute",
top: 0,
left: 0,
width: "100%",
"z-index": 99999,
display: "none",
height: a(document).height()
})
}, _show_overlay = function () {
c.is(":visible") || c.fadeIn("fast")
}, _hide_overlay = function () {
c.is(":visible") && c.hide()
}, _add_buttons = function () {
a("a[rel=popup-close]").click(function () {
return _hide_box(), !1
}), a("a[rel=popup-open]").click(function () {
return _show_box(), !1
})
}, _show_box = function () {
if (!a("#popup-box").is(":visible")) {
_show_overlay(), a("#popup-box").fadeIn("fast");
var b = a("html");
b.data("scroll-position", d), b.data("previous-overflow", b.css("overflow")), b.css("overflow", "hidden"), window.scrollTo(d[0], d[1])
}
}, _hide_box = function () {
if (a("#popup-box").is(":visible")) {
var b = a("html"),
c = b.data("scroll-position");
b.css("overflow", b.data("previous-overflow")), window.scrollTo(c[0], c[1]), _hide_overlay(), a("#popup-box").hide()
}
}, _init()
}
})(jQuery)

You can write your content directly in your JS as a string and then use the innerHTML property of elements to set their value. You can do this in pure JS as follows.
var popup = document.getElementById("popup-box");
var html = "This is the pop up content. The quick brown fox jumps over the lazy dog.";
popup.innerHTML = html;
And you can do this in jQuery as follows:
$('#triggerforpopup').on('click', function() {
$("#popup-box").html(html); // Where html is a variable containing your text.
});
Note: You can write in HTML tags and the like in your html string and they will be rendered as you would expect on the page. You are not limited to plaintext.
Note: live has been deprecated in jQuery as of jQuery 1.7. It has been replaced with on. See http://api.jquery.com/live/ and http://api.jquery.com/on/.
If you want to include everything in the JavaScript as mentioned in the comments, you can do this:
var popup = document.createElement("div");
popup.id = "popup-box";
popup.innerHTML = "your html here";
document.getElementById("parent element id").appendChild(popup);
What this does is create a new div element, set its id and then append it as the child element of the parent of your choice. You could just do a plain insert of the HTML string into another element, but by creating an element here you have a bit more flexibility regarding its placement.

use
var popupHtml = $('<div>This is the pop up content. The quick brown fox jumps over the lazy dog.</div>');
popupHtml.popup();
I found lots of issues in the popup plugin you have used. Fixed them to make it working. Have a look http://jsbin.com/oyamiy/6/watch

Related

Different jQuery UI behavior in different browsers

I have a very simple calendar. When clicking any date a jQuery dialog gets opened, the user clicks a button, the dialog closes, the clicked button's value gets appended to the clicked element and after that all clicked elements get saved to an array.
I have created a JSBin.
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
Click me
<div id="dialog"></div>
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</body>
</html>
js:
$('.cal_clean_active').click(function(e) {
var that = $(this);
var dates = new Array();
that.toggleClass('clicked');
$('#dialog').dialog({
resizable: false,
height: "auto",
width: "auto",
modal: true,
buttons: {
"Vormittags (bis 12:00 Uhr)": function() {
that.attr('slot','vormittags');
console.log(that.attr('slot'));
$(this).dialog('close');
}
},
beforeClose: function() {
$('.clicked').each(function(i, val) {
dates.push(val.id + '|' + val.slot);
});
console.log(dates);
}
});
});
In Chrome everything works as expected (Console output is 2016-11-01|vormittags) in every other tested Browser (Firefox, Edge, IE) the console output is 2016-11-01|undefined. Any help would be appreciated.
The problem is that slot is not a standard attribute for an element. In most browsers, it is hence not included in the standard properties of an element (like element.value or element.id). Chrome seems to handle this situation differently than the other browsers.
Two bad solutions
A solution would be to change:
dates.push(val.id + '|' + val.slot);
to
dates.push(val.id + '|' + $(val).attr('slot'));`.
Another - plain javascript - solution could be to use the javascript getAttribute() method. This would work because in the jQuery source code custom attributes are set with this line:
elem.setAttribute( name, value + "" ); //from the jQuery source code
Thus making it possible to also read them with element.getAttribute(). Your line would then look like this:
dates.push(val.id + '|' + val.getAttribute("slot"));
The better solution
This might all work, but it still is not considered good code. In your code the attribute slot is used to store data. From the .data() jQuery docs (see this answer):
Store arbitrary data associated with the specified element. Returns the value that was set.
$.attr() on the contrary is used to manipulate attributes, like id, value or type. The clean way of solving this problem would be:
$('.cal_clean_active').click(function(e) {
var that = $(this);
var dates = new Array();
that.toggleClass('clicked');
$('#dialog').dialog({
resizable: false,
height: "auto",
width: "auto",
modal: true,
buttons: {
"Vormittags (bis 12:00 Uhr)": function() {
that.data('slot','vormittags'); //Not the use of data
console.log(that.data('slot'));
$(this).dialog('close');
}
},
beforeClose: function() {
$('.clicked').each(function(i, val) {
dates.push(val.id + '|' + $(val).data("slot")); //Also note it here
});
console.log(dates);
}
});
});

JavaScript detect in which element an object is created

Note:
This question is marked as a duplicate but I'm not looking to get the script element but the div element as seen in my code where the script is in.
Whereas the "duplicate" is looking to get the script tag. this is not the case with my script.
I am using JavaScript for my current project and was wondering if there is a way to detect which HTML element an object was created in.
Consider the following code.
Editable.js
function Editable(elem, form1, form2) {
this._edit_form;
this._value_form;
this._current_form;
//Getters
this.getEditForm = function() { return this._form1; };
this.getValueForm = function() { return this._form2; };
this.getCurrentForm = function() { return this._current_form; };
//Setters
this.setCurrentForm = function(current_form) { this._current_form = current_form; };
this.switch = function() {
if(_current_form == _edit_form)
_current_form = _value_form;
else
_current_form = edit_form;
};
var __construct = function() {
$(this.elem).html(this._value_form);
}();
}
-
<html>
<head>
<script src='Editable.js'></script>
</head>
<body>
<div>
<script>new Editable(this, "Company Name", "<input type='text' placeholder='enter a company name' />");</script>
</div>
</body>
</html>
The point of an editable is that it has a value form and an edit form.
I want to be able to switch between those by removing the text from the element and placing an HTML Input field.
This change is supposed to happen when clicking the element.
The problem now is that "this" logs as
Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
While the object would need to know what element it is in so it may edit it's contents.
So I would need the DIV HTML element for that.
Thank you very much.

JQuery partly triggered

I'm a beginner with JQuery and I was trying to create a button that dynamically changes the colors defined in the CSS depending on what color it is right now (just switch between blue / red) and also change the text on the button.
The .draggable() part executes just fine and so does the first and last console.log, so everything but the part within the click event handler works ... but why?
Relevant html code:
<!DOCTYPE html>
<html>
<head>
<title>Meine Website</title>
<meta charset="utf-8">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript">
</script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"
type="text/javascript">
</script>
<script src="home_jquery.js"></script>
<script src="home_javascript.js"></script>
<link rel="stylesheet" type="text/css" href="home_style_blau.css">
</head>
<body>
<input type="button" id="farbwechsel_button" value="Rot" />
/* rest of html (taschenrechner_box, etc.) */
</body>
Here's the jQuery part:
var blau = true;
$(document).ready(function () {
$('#taschenrechner_box').draggable();
console.log("test1");
$('#farbwechsel_button').click(function() {
console.log("test2");
if (blau == true) {
console.log("blau = " + blau);
$('body').css({"background-color": "8b0000"});
$('#farbwechsel_button').value = "Blau";
blau = false;
}
else {
console.log("blau = " + blau);
$('body').css({"background-color": "lightsteelblue"});
$('#farbwechsel_button').value = "Rot";
blau = true;
}
console.log("test3");
})
console.log("test4");
});
In your HTML you have:
<input type="button" id="farbwechsel_button" value="Rot" />
But in your JS you refer to
$('#farbwechel_button').click(function() {
Note the forgotten s in your JS. So the JS should be:
$('#farbwechsel_button').click(function() {
Edit: you've forgotten the s in al your referrals to the button. Don't forget to add it everywhere. You've also forgotten a ; just before the last console.log() function.
Edit 2: Here's a Fiddle with a working example. It's pretty much self explanatory. In this case you preferably should make use of classes which you toggle on pressing the button.

JavaScript hide and show toggle, hide DIV

For the following example, how would I start the page off by hiding the 'divToToggle' DIV as it is currently showing on default? I do not want to use 'display:none;' outside of the script for accessibility reasons. How do you hide the 'divToToggle' within the script on startup?
Thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript hide and show toggle</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<script>
function toggleAndChangeText() {
$('#divToToggle').toggle();
if ($('#divToToggle').css('display') == 'none') {
$('#aTag').html('[+] Show text');
}
else {
$('#aTag').html('[-] Hide text');
}
}
</script>
<br>
<a id="aTag" href="javascript:toggleAndChangeText();">[-] Hide text</A>
<div id="divToToggle">Content that will be shown or hidden.</div>
</body>
</html>
Just use the hide function inside a document.ready function
$(function(){
$('#divToToggle').hide();
});
Just use jQuery, since you're already using it (and this way doesn't prevent non-JS users from seeing the element):
function toggleAndChangeText() {
$('#divToToggle').toggle();
if ($('#divToToggle').css('display') == 'none') {
$('#aTag').html('[+] Show text');
}
else {
$('#aTag').html('[-] Hide text');
}
}
$('#divToToggle').hide();
// the rest of your script(s)...
Also, a minor update to your toggle function:
function toggleAndChangeText() {
// because you're accessing this element more than once,
// it should be cached to save future DOM look-ups
var divToToggle = $('#divToToggle');
divToToggle.toggle();
// You're not changing the HTML, just the text, so use the
// appropriate method (though it's a *minor* change)
$('#aTag').text(function() {
// if the element is visible change the text to
// '...hide...'; if not, change the text to '...show...'
return divToToggle.is(':visible') ? '[-] Hide text' : '[+] Show Text';
});
}
References:
hide().
is().
text().
:visible selector.

Google Custom Search on submit

I would like to customize my search form. I am using Google Search Service and have it linked to my domain and so on.
I chose the two column layout in the Control Panel, but however, I want to do something onSubmit of the form.
So I tried to put an actionlistener in jQuery into the form, however does not work.
Then I thought google certainly provides something for that. And yes they do. It is called:
setOnSubmitCallback()
http://code.google.com/apis/websearch/docs/reference.html
Unfortunately I dont get it.
So far I have:
google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
function initialize()
{
var searchControl = new google.search.CustomSearchControl('017998360718714977594:j6sbtr-d6x8');
searchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
searchControl.draw('cse', options);
}
google.setOnLoadCallback(initialize);
So i have two divs:
#cse-search-form for the form and #cse for the results
#cse is in another div #searchResults, that is hidden and here it comes:
I want to open #searchResults in a dialog from jQuery UI.
$("#searchResults").dialog( { minWidth: 750, minHeight: 750 } );
Which will result into:
.setOnSubmitCallback(function() {
$("#searchResults").dialog( { minWidth: 750, minHeight: 750 } );
} );
So my problem now is, where and on what do I have to put the setOnSubmitCallback?
I cannot put it on google.search.Search or CustomSearchControl as it is stated in the documentation. ANd I cannot call it in the onLoadCallback so it is very strange for me. Cannt figure out how to do that.
I hope somebody has some more experience for the google search and could help me out with a solution.
Thank you very much in advance.
NOTE: the code below is using something Google deprecated. Use this instead: http://code.google.com/apis/customsearch/v1/overview.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Hello World - Google Web Search API Sample</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
//<![CDATA[
google.load('search', '1');
google.load("jquery", "1.5.2");
google.load("jqueryui", "1.8.12");
function OnLoad() {
var searchComplete = function(searchControl, searcher){
$('#searchResults').dialog({modal: true, width: 700, height: 400, position: [50, 50]});
for (result in searcher.results) {
var content = searcher.results[result].content;
var title = searcher.results[result].title;
var url = searcher.results[result].url;
$('#searchResults ul')
.append($('<li></li>')
.append($('<a/>').attr('href', url).text(title))
.append($('<p/>').text(content)));
}
};
// called on form submit
newSearch = function(form) {
if (form.input.value) {
// Create a search control
var searchControl = new google.search.SearchControl();
// Add in a set of searchers
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.VideoSearch());
// tell the searchControl to draw itself (without this, the searchComplete won't get called - I'm not sure why)
searchControl.draw();
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setSearchCompleteCallback(this, searchComplete);
searchControl.execute(form.input.value);
}
return false;
}
// create a search form without a clear button
// bind form submission to my custom code
var container = document.getElementById("searchFormContainer");
this.searchForm = new google.search.SearchForm(false, container);
this.searchForm.setOnSubmitCallback(this, newSearch);
}
google.setOnLoadCallback(OnLoad);
//]]>
</script>
</head>
<body>
<div id="searchFormContainer">Loading</div>
<div id="searchResults" title="Search Results">
<ul></ul>
</div>
</body>
</html>

Categories

Resources