Difference between executing in JS console and as script - javascript

I have a website with links, which should open a Lightbox (3rd party plugin Magnific Popup / jquery). After manipulating content on the site, i have to re-execute some Javascript of the Lightbox plugin, so that it recognizes the new links as links to lightboxes.
function loadLightbox() {
console.log("Lightbox start"); // for debugging
$('a.img').magnificPopup({
type: 'image',
closeOnContentClick: true,
closeBtnInside: false,
image: {
titleSrc: 'title_off',
markup:
'<div class="mfp-figure">' +
'<div class="mfp-close"></div>' +
'<div class="mfp-title"></div>' +
'<div class="mfp-img"></div>' +
'<div class="mfp-bottom-bar">' +
'<div class="mfp-counter"></div>' +
'</div>' +
'</div>' // Popup HTML markup. `.mfp-img` div will be replaced with img tag, `.mfp-close` by close button
}
});
console.log("Lightbox end"); // for debugging
}
I have a function, which manipulates the content on the page changeSuggestion(). Because I want to have the content changed every 6 secondes, I use the setInterval function.
setInterval(function () { changeSuggestion(); loadLightbox(); }, 6000);
My problem is, that it changes every 6s the content on the page, but the lightbox thing doesn't work (although the lightbox function produces output). But when I copy the loadLightbox() function into the firefox console and execute it, the lightbox in does work until it changes the content again. So my question is, what is the difference between executing via setInterval and executing in the Firefox javascript console?
Edit:
changeSuggestion: opens a JSON file, and produces html-formatted output, the page is manipulated by $("#blogSuggestion").html(result)
<!-- language: lang-js -->
function changeSuggestion() {
$.getJSON("blog/blog.json", function (data) {
var n = 0,
showId,
entry,
result;
$.each(data.blogentries, function (key, entry) {
if (entry.id > n) {
n = entry.id;
}
});
showId = randomIntFromInterval(0, n - 1);
if (data.blogentries[showId]) {
entry = data.blogentries[showId];
if (entry.type === "text") {
result = "<a class=\"" + entry.type + "\" title=\"" + entry.title + "\" href= \"#blogID" + entry.id + "\"><b>" + entry.title + "</b>";
} else {
result = "<a class=\"" + entry.type + "\" title=\"" + entry.title + "\" href= \"" + entry.source + "\"><b>" + entry.title + "</b>";
}
if (entry.content) {
result = result + "<br /><p>" + getExcerpt(entry.content, 20, '') + "</p><div id= \"blogID" + entry.id + "\" class=\"blogLightbox mfp-hide\"><img alt=\"" + entry.title + "\" src=\"" + entry.thumb + "\" ><div class=\"blogText\"><h3>" + entry.title + "</h3><p>" + entry.content + "</p></a></div></div>";
} else {
result = result + '<img alt=\"' + entry.title + '\" src=\"' + entry.thumb + '\"></a>';
}
$("#blogSuggestion").html(result);
} else {
console.log("Nothing with ID: " + showId);
}
});
Edit:
As its written in the comments, the content is changed asynchronously. If I put the asynchronously function into the body of changeSuggestion it works!

Related

Im getting objectHTMLimageElement instead of the image in my list item

function story(){
if(document.getElementById("area").value == "salwa"){
var oImg = document.createElement("img");
oImg.setAttribute('src', './images/logo.png');
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '1px');
oImg.setAttribute('width', '1px');
document.body.appendChild(oImg);
document.getElementById("story-result").innerHTML += "<li>" + oImg + " </li>";
}else{
document.getElementById("li-result").innerHTML += "<h1>" + "no results" + " </h1>";
}
}
Is this working?
function story(){
if (document.getElementById("area").value == "salwa"){
document.getElementById("story-result").innerHTML = "<img src=" + "'./images/logo.png'" + "alt=" + "'na'" + "height=" + "'1px'" + "width=" + "'1px'" + ">" + "</img>";
} else {
document.getElementById("li-result").innerHTML += "<h1>" + "no results" + " </h1>";
}
}
You have to get the image source attribute and make it equal to the innerHTML of the element with id story-result.
You are currently using the image itself, not its src attribute.
Try this:
document.getElementById("story-result").innerHTML += "<li>" + oImg.getAttribute('src') + " </li>";

How do I fix issues with using both javascript in an external file and javascript within html

I am building a TV application.
it uses keypress navigation
the application should display performance details as well because there won't be access to developer tools
This is my code to get the performance details
<script>
window.onload = function () {
if ("timing" in window.performance) {
document.getElementById("total_download_time").innerHTML = "<span class='color-class'>Page download time :</span> " + "<span class='color-class'>" + (window.performance.timing.responseEnd - window.performance.timing.navigationStart) + " <span class='color-class'>ms</span>";
document.getElementById("total_render_time").innerHTML = "<span class='color-class'>Page rendering time :</span> " + "<span class='color-class'>" + (window.performance.timing.loadEventStart - window.performance.timing.domLoading) + "</span>" + "<span class='color-class'> ms</san>";
document.getElementById("latency").innerHTML = "<span class='color-class'>Latency :</span> " + "<span class='color-class'>" + (window.performance.timing.responseStart - window.performance.timing.fetchStart) + "</span>" + "<span class='color-class'> ms</san>";
document.getElementById("dom_lookup_time").innerHTML = "<span class='color-class'>Dom Lookup Time :</span> " + "<span class='color-class'>" + (window.performance.timing.domainLookupEnd - window.performance.timing.domainLookupStart) + "</span>" + "<span class='color-class'> ms</san>";
document.getElementById("server_connect_time").innerHTML = "<span class='color-class'>Server Connect time :</span> " + "<span class='color-class'>" + (window.performance.timing.connectEnd - window.performance.timing.connectStart) + "</span>" + "<span class='color-class'> ms</san>";
document.getElementById("page_load_time").innerHTML = "<span class='color-class'>Page Load time :</span> " + "<span class='color-class'>" + (window.performance.timing.loadEventStart - window.performance.timing.navigationStart) + "</span>" + "<span class='color-class'> ms</san>";
document.getElementById("redirection_time").innerHTML = "<span class='color-class'>Redirection time :</span> " + "<span class='color-class'>" + (window.performance.timing.redirectEnd - window.performance.timing.redirectStart) + "</span>" + "<span class='color-class'> ms</san>";
document.getElementById("dom_content_load_time").innerHTML = "<span class='color-class'>Dom Content Load time :</span> " + "<span class='color-class'>" + (window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart) + "</span>" + "<span class='color-class'> ms</san>";
}
else {
document.getElementById("result").innerHTML = "Page Timing API not supported";
}
}
</script>
I have written this in the HTML file itself
However, I have another .js file which has the code required for keypress navigation
key_navigation.js
function init() {
document.addEventListener("keydown", function (e) {
if (eventExec(e.keyCode))
e.preventDefault();
}, false);
document.addEventListener("keydown", function (e) {
if (handleKeyCode(e.keyCode))
e.preventDefault();
}, false);
// set appMngr to the application/oipfApplicationManager object
var appMgr = document.getElementById("oipfID");
if (typeof (appMgr.getOwnerApplication) != "undefined") {
// create the application
int_app = appMgr.getOwnerApplication(document);
//setting remote control buttons
int_keyset = int_app.privateData.keyset;
int_ksVisible = 0x23F;
int_app.show();
int_keyset.setValue(int_ksVisible);
}
}
The keypress works fine when the script for performance is not added.
Once I add the performance script , the keypress navigation doesnt work.
How can I fix this?

How to add event handlers to dynamically created buttons in jQuery?

I used AJAX to dynamically create the HTML but I've encountered a problem
<script>
function page_loaded(){
jQuery.ajax({
method: "GET",
url: "get_data_dashboard.php",
success: function(data){
var markers = JSON.parse(data);
for(var i = 0; i < markers.length; i++){
var m = markers[i];
var markerHTML = "<div class='marker'>" +
"<span id='naziv'>Naziv zahtjeva: " + m.naziv + "</span></br>" +
"<span id='ulica'>Ulica: " + m.ulica + "</span></br>" +
"<p id='opis'>Opis:</br>" + m.opis + "</p></br>" +
"<span id='email'>Email: " + m.email + "</span></br>" +
"<img id='slika' src='" + m.link_slike + "' />" + "</br>" +
"<textarea rows='5' cols='30' maxlength='500' id='t" + m.marker_id + "' placeholder='Komentar'>" + "</textarea></br>"
+ "<div class='buttons'><a href='odobri_prijavu.php?id=" + m.marker_id + "'>Odobri</a>" +
"<a href='izbrisi_prijavu.php?id=" + m.marker_id + "'>Izbriši</a>" + "</div>" +
"</div><hr>";
$('#content').append(markerHTML);
}
}
})
}
$(document).ready(page_loaded());
</script>
I tried to use buttons first instead of anchor tags but I couldn't figure how to add event handlers to dynamically created buttons that will post a request via AJAX to some php script with the proper id as the value and the value of the textarea. So I used the anchor tag and I was able to send the id, but I can't send the value of the textarea because I don't know how to reference it and even if I referenced it, it will be NULL because its value is set to the anchor tag at the very beginning and I want to type in text in the textarea.
Instead of listening to individual "elements", you can actually listen to a parent of a specific element (You'll need to supply another parameter to on()). A popular pattern is to listen to "body" (because body is a parent to all, technically), but any non-dynamic parent element will work! Here's an example:
//notice the second parameter supplied
$("body").on("click", ".my-dynamic-element", function(e){
//awesome code that makes the world a better place goes here
//this code triggers when .my-dynamic-element is clicked, wootz
});
Event delegation is your friend.
I don`t see any actions that actually do event handling, but a simple solution would be something like:
$(document).on('click', '.your-button-class', function(){
// do your thing
});
<script>
function page_loaded(){
jQuery.ajax({
method: "GET",
url: "get_data_dashboard.php",
success: function(data){
var markers = JSON.parse(data);
for(var i = 0; i < markers.length; i++){
var m = markers[i];
var markerHTML = "<div class='marker'>" +
"<span id='naziv'>Naziv zahtjeva: " + m.naziv + "</span></br>" +
"<span id='ulica'>Ulica: " + m.ulica + "</span></br>" +
"<p id='opis'>Opis:</br>" + m.opis + "</p></br>" +
"<span id='email'>Email: " + m.email + "</span></br>" +
"<img id='slika' src='" + m.link_slike + "' />" + "</br>" +
"<textarea rows='5' cols='30' maxlength='500' id='t" + m.marker_id + "' placeholder='Komentar'>" + "</textarea></br>"
+ "<div class='buttons'>Odobri" +
"<a href='izbrisi_prijavu.php?id=" + m.marker_id + "'>Izbriši</a>" + "</div>" +
"</div><hr>";
$('#content').append(markerHTML);
}
}
})
}
$(document).ready(page_loaded());
function clickHandler(id){
$('#'+id) // selects the button
$('#t'+id) // selects the text area
}
</script>

Caret not shown in empty iframe

I am trying to implement my own rich text editor using iframe. However, whenver I click inside the empty rich text editor, the caret or mouse cursor doesn't show up. After checking on google, I found that we need to add some html to the iframe beforehand such as 'break tag. But my code below will only add the break tag to the first rich text editor and not to the second. Not sure what I am doing wrong here.......
$.fn.createRichTextEditor = function(width,height="auto") {
var iframeDocument;
var iframeDocumentId = this.attr("id") + "-rte-editor";
var newHtml = "<div id='rte-" + iframeDocumentId + "' class='rte'>" +
"<ul class='rte-toolbar'>" +
"<li id='bold'><button id='rte-boldBtn-" + iframeDocumentId + "' class='rte-button' value='bold' title='Bold'></button></li>" +
"<li id='italic'><button id='rte-italicBtn-" + iframeDocumentId + "' class='rte-button' value='italic' title='Italic'></button></li>" +
"<li id='underline'><button id='rte-underlineBtn-" + iframeDocumentId + "' class='rte-button' value='underline' title='Underline'></button></li>" +
"<li id='createLink'><button id='rte-createLinkBtn-" + iframeDocumentId + "' class='rte-button-link' value='createLink' title='Link'></button></li>" +
"<li id='unlink'><button id='rte-unlinkBtn-" + iframeDocumentId + "' class='rte-button-link' value='unlink' title='Unlink'></button></li>" +
"</ul>" +
"<iframe class='rte-iframe' id='" + iframeDocumentId + "' frameBorder='0'></iframe>" +
"</div>";
this.after(newHtml);
this.css('display', 'none');
var iframe = document.getElementById(iframeDocumentId);
var rte = iframe.parentElement;
$(rte).css('width', width);
$(rte).css('border', '1px solid #ccc');
$(iframe).on('load', function() {
$(iframe).width("100%");
$(iframe).height(height);
iframeDocument = iframe.contentDocument;
iframeDocument.designMode = 'On';
$(iframeDocument).find('body').html('<br><br/>');
});
};
You need to loop through each matching element in your plugin:
$.fn.createRichTextEditor = function (width, height) {
this.each(function () {
// Your code for each element here
});
});

display: none still inheriting

A dynamically created form is rendering strangely even with the style sheet disabled.
the form shows and hides a wide range of details based on which options are selected.
so, for example, a number of the following will have been rendered with C#.net ...
formOutput += "<div class=\"field textBox\" id=\"" + field.Id + "\"><div class=\"labelTB\"><label for=\"" + field.Id + "\" class=\"" + reqClass + "\">" + field.Name + requirement + "</label></div>" +
"<input type=\"text\" class=\"numInput\" id=\"" + field.Id + "_tb\" name=\"" + field.Name + "\" onkeyup=\"Service.refresh(this); numCheck(this)\" onclick=\"numCheck(this)\" />" +
// numButtons:
"<div class=\"minus plusMinus\" id=\"minus_" + field.Id + "\" onmousedown=\"numBox(this)\" /></div>" +
"<div class=\"plus plusMinus\" id=\"plus_" + field.Id + "\" onmousedown=\"numBox(this)\" /></div></div><br />";
...and then the parent node is hidden onload by JS:
var setVisibility = function (id, bool) {
try {
get(id).style.display = (bool) ? "block" : "none";
} catch (e) {
return false;
}
return bool;
}
However, when there are a large number of hidden fields, I am getting a considerable space in the middle of my form.
I have tried all sorts of solutions with little success. simply moving everything up is not easily viable (the form is much much more complicated than I can show here)...
i have even tried the following:
var setVisibility = function (id, bool) {
try {
get(id).style.display = (bool) ? "block" : "none";
get(id).style.position = (bool) ? "relative" : "absolute";
get(id).style.height = (bool) ? "auto" : "0px";
var children = get("containerType").childNodes
for (var i in children) {
if (children[i].style) {
children[i].style.display = (bool) ? "block" : "none";
children[i].style.position = (bool) ? "relative" : "absolute";
children[i].style.height = (bool) ? "auto" : "0px";
}
}
} catch (e) {
return false;
}
return bool;
}
what is causing this problem? is there a solution?
(see image below)
You have a br-tag at the end of you code (after the div with id=plus_??) which will always display, regardless of whether you hide the divs or not. You could but the br-tag inside one of the divs to achieve what you want
formOutput += "<div class=\"field textBox\" id=\"" + field.Id + "\"><div class=\"labelTB\"><label for=\"" + field.Id + "\" class=\"" + reqClass + "\">" + field.Name + requirement + "</label></div>" +
"<input type=\"text\" class=\"numInput\" id=\"" + field.Id + "_tb\" name=\"" + field.Name + "\" onkeyup=\"Service.refresh(this); numCheck(this)\" onclick=\"numCheck(this)\" />" +
// numButtons:
"<div class=\"minus plusMinus\" id=\"minus_" + field.Id + "\" onmousedown=\"numBox(this)\" /></div>" +
"<div class=\"plus plusMinus\" id=\"plus_" + field.Id + "\" onmousedown=\"numBox(this)\" /></div><br /></div>";
...or you could just provide the br-tag with a class or id and use that to show and hide along with the divs

Categories