Conflict between Lightbox and JavaScript - javascript

I have researched thoroughly for solutions for this issues but could not find anything since I don't use $ tags.
Actually I tried to put Lightbox on my page and a JavaScript slideshow, but it seems like only the slideshow would work and the lightbox gets disabled when I add both.
<link href="css/lightbox.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="style.css" />
My JavaScript slideshow
<script type="text/javascript">
var Image = new Array("images/food1.jpg", "images/food2.jpg", "images/food3.jpg");
var Image_Number = 0;
var Image_Length = Image.length - 1;
function change_image(num) {
Image_Number = Image_Number + num;
if (Image_Number > Image_Length) {
Image_Number = 0;
}
if (Image_Number < 0) {
Image_Number = Image_Length;
}
document.slideshow.src= Image[Image_Number];
return false;
}
function auto() {
setInterval("change_image(1)", 3000);
}
</script>
//lightbox: importing the lightbox
<script src="js/jquery-1.10.2.min.js">;</script>
<script src="js/lightbox-2.6.min.js">;</script>

I did not went detail on your code, but that simpton you discribed seems like you are having a script conflict, a rule is that if you can only call a script once in your website here I'll give you an example of an issue I had... so just call a script once for as many plugins or modules using the script...
In the HTML codes, please remove the line marked by red. It's because the jQuery has already been added in the header section.

Related

html <link> and <script> tags not working with jquery .on('load') event listener

In my project, I am designing a page load progress bar like Youtube. For that, I am capturing all the rich element tags like img, iframe, video, audio etc, and controlling the width of the progress bar as and when each of the tags are getting loaded. You can have a look at the code below.
var media_nos = $("body img").length + $("body iframe").length + $("body video").length + $("link").length + $("body script").length;
console.log(media_nos);
doProgress();
// function for the progress bar
function doProgress() {
$("body img, body iframe").on('load', function() {
loading.loaded++;
console.log(loading.loaded);
var newWidthPercentage = (loading.loaded / media_nos) * 100;
animateLoader(newWidthPercentage + '%');
}).each(function(){
if(this.complete) {
$(this).trigger('load');
}
});
$('body video').on('canplaythrough', function() {
loading.loaded++;
var newWidthPercentage = (loaded / media_nos) * 100;
animateLoader(newWidthPercentage + '%');
}).each(function(){
if(this.complete) {
$(this).trigger('load');
}
});
}
//Animate the loader
function animateLoader(newWidth) {
$("#progressBar").width(newWidth);
if(loading.loaded==media_nos){
setTimeout(function(){
$("#progressBar").animate({opacity:0});
},500);
}
}
But, the problem here is I am not able to track the loading of the link and script tags using the jquery .on('load') method as I did for img, iframe tags etc. It works if I write an inline onload attribute to link tags as shown below.
<link rel="stylesheet" href="css/bootstrap.min.css" onload="load();">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" onload="load();">
<link rel="stylesheet" href="css/style.css" onload="load();">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" onload="load();">
main.js
var loading = {"loaded" : 0};
function load() {
console.log("hello");
loading.loaded++;
console.log(loading.loaded);
}
As you will know, its very hectic to write an inline onload for every such link and script tags, is there any way I can track the loading of the link and script tags in a better way like the .on('load') method? Thanks in advance.

clearInterval() not working on clock timer with JavaScript

I am very new to JavaScript and programming in general. I am currently in a little pickle with some code that I am playing around with, and I am wondering if anyone can give me some advice.
Background:
The code I am working with is rather simple; There is a clock with the current time running on setInterval to update by the second.
Below the clock there is a button that reads “Stop,” and when pressed, it will clear the Interval and the button will then read “Start.” If the button, which reads “Start” is pressed again, it will continue the clock timer in its current time. So basically this one button toggles the interval of the clock, and depending on which state it is, the button will read “Start” or “Stop.”
W3Schools: JS Timing is where I am originally referencing when creating the code I am working with. This is where I am learning about how setInterval and clearInterval works. I also took some of the code in the examples and adjusted it so I can try to make the clock timer toggle off and on.
Code:
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
https://jsfiddle.net/dtc84d78/
Problem:
So my problem with the code is that the button toggles from a “Stop” button to a “Start” button, but the clearInterval is not applying to the Variable with the setInterval.
I have googled similar problems in SO, such as this one, and I followed their advice, and still nothing. After hours of trying to figure out, I decided to just copy and paste some example from W3Schools straight to jsFiddle, and that didn’t even work (included in jsfiddle link)?
I am really just going crazy on why anything with clearInterval() is not working with me? Could it be my computer, browser or anything else? I am coming to SO as my last resource, so if anyone can give me some guidance to this problem, I will name my first child after you.
Thank you in advance.
Extra Info:
I am currently working on a Mac desktop, using Komodo to write the code, and I am using Google Chrome to preview the code.
UPDATE:
I mentioned this in the comments, but coming in the code was in an external .js file. The .js file was then linked in between the head tags, and right before the end body tag.
<head>
<meta charset="utf-8" />
<title>Program</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/program-05.css">
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
</head>
<body onload="checkCookies(); setTimeout(function() { func11() }, 5000);">
. . . code for stuff
. . . code for clock timer
. . . code for other stuff
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
</body>
After #Matz mentioned to stick the clock timer js code in the head section, the code worked great! This is what it looks like so far in the head section.
<head>
<meta charset="utf-8" />
<title>Program</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/program-05.css">
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
<script>
///*
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
//*/
</script>
</head>
Though this works great, I now want to figure out as to why the clock timer js code works when it is directly in the head section as compared to keeping it in the external .js file (with the external file being linked in the doc)? What can I do to make it work within the external file?
Problem:
This is because the default Load Type is set to onLoad which is wrapping your javascript code in window.onload = function() {} hence the scope of your function was getting limited to the onload function and it wasn't available outside:
Solution:
Click on the Javascript setting in the Javascript section of the Fiddle, change it to No wrap - in body and it will work since this will now place your Javascript code in the body tag.
Additional Note:
Your code is also working via StackOverflow snippet:
/*My Problem*/
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
/*W3S Problem*/
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML =
d.toLocaleTimeString();
}
<!-- My Problem -->
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
<hr>
<hr>
<!-- W3S Problem -->
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
Recommendation
Separation of concerns
I'll recommend you moving your javascript code in the external file and later include them in your HTML using script tag. So for example, you moved your code in app.js then include that in your HTML as:
<!-- make sure the path here is relative to the current HTML -->
<script src="./app.js"></script>
One way to fix the timer starting and stopping is to move the javascript in between the HEAD tags so the functions are declared by the time the html loads. I made this work:
<html>
<head>
<title>Stuff</title>
<script >
var clock09 = window.setInterval(myTimer09, 1000);
.... your code
</script>
</head>
<body>
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
</body>
</html>
You are declaring a new date variable in the myTimer09 function, so every time it is called, it shows the current time. You should declare the time outside the function, then pass it to the function. When you stop the timer, you should save the time value so that you can restart with that value.
This seems to be an issue with JSFiddle.
The onclick handler is looking for window.toggle10 which isn't actually defined (check for the error in the console).
It seems that this is something others have seen with JSFiddle
I've C&Ped your code in to a JSbin and it works as described!

How to load js/css files in custom popup load

In my project i am displaying a custom pop up page like below by javascript which has a form for user to fill,then I need to load some js files when pop up is loaded.
how to load js files,plz help.
<html>
<head>
<script type='text/javascript' src='files/jsfiles/core.js'></script>
</head>
<body>
<!- I need to call javascript function showUsers() from here->
<input type='button' onclick='showUsers();' value='listUsers'>
</body>
</html>
function loadScript(src) {
var script = document.createElement("script");
script.async = false;
script.src = src;
document.head.appendChild(script);
};
function loadStyle(src) {
var style = document.createElement("link");
style.rel = "stylesheet";
style.href = src;
document.head.appendChild(style);
};
function loadFiles() {
var scriptsArray = ['src1url', 'src2url'.., 'scrnurl'];
var csssArray = ['src1url', 'src2url'.., 'scrnurl'];
for (var i = 0; i < scriptsArray.length; i++) {
loadScript(scriptsArray[i]);
}
for (var i = 0; i < csssArray.length; i++) {
loadStyle(csssArray[i]);
}
};
function yoursubmitFcn(callback) {
// your functionality here;
callback();
}
$(document).ready(function () {
// do your stuff
yoursubmitFcn(loadFiles);
});
Also check: Another short form
You can use this library fancybox
Loading jQuery from CDN
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<link rel="stylesheet" href="/fancybox/jquery.fancybox-1.3.4.css" type="text/css"
media="screen" />
html
Sign in
JS
$('.open_pop').fancybox({
});
function openmsg_sent() {
jQuery(".open_pop").trigger("click");
}
For better and consistent UI, you can use a div which you can display with fixed positioning on click of the button.
I believe Alert wont be able to display css properties if am not wrong.
What you can do is, onclick of the button, in the JS, you can put your popup content into a div which is hidden initially and shown on click.
Hope this helps.

Background Image Rotator

I need some suggestions and ideas to improve a background image rotator.
The script as of now is very basic but I'm looking to change 2 thing.
I want the images to fade into each other.
I need to be able to preload the images so it doesn't have the delay when loading them when they first display.
Thoughts?
<script type="text/javascript">
var images = ['bg1.png', 'bg2.png', 'bg3.png'];
var curImage = 0;
function switchImage()
{
curImage = (curImage + 1) % images.length
document.body.style.backgroundImage = 'url(images/' + images[curImage] + ')'
}
window.setInterval(switchImage, 5000);
</script>
Example: http://www.nickersonweb.com/demo/PMS/index.html
For fading, try fadeOut() and fadeIn() with jQuery. (Demo and documentation here: http://api.jquery.com/fadeOut/, http://api.jquery.com/fadeIn/)
For preloading, trying making an invisible image somewhere on the page, like this:
<img src='bg1.png' width="0" height="0">
Another way to preload the images is using javascript to create an image object. Here's the code I used for something similiar.
var imgnum=0;
var imgsrcs=new Array("imgs/img1.jpg","imgs/img2.jpg")
var fimgs=new Array();
var imgid="imgid";
function timedCount()
{
$("#"+imgid).fadeTo(1000,0,function(){newimage();
});
setTimeout(timedCount,5000);
}
function newimage()
{
imgnum=(imgnum+1)%imgsrcs.length;
document.getElementById(imgid).src=fimgs[imgnum].src;
$("#"+imgid).fadeTo(1000,1);
}
function initializeslideshow()
{
var i;
for(i=0;i<imgsrcs.length;i++)
{
fimgs[i]=new Image(270,270)
fimgs[i].src=imgsrcs[i];
}
}
initializeslideshow();
setTimeout(timedCount,5000);
You'll need to link to jQuery (and jQuery UI, I think) to use the code above, like this, for instance:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>

CSS switcher - looking for more seamless implementation

I'm using a JS CSS switcher to good effect really brilliant. However, I would be delighted if it worked more seamlessly. At the point of opening a new page on the site the default css style often flickers on breifly, before the cookie re-applies the selected CSS style.
e.g. the canvas style is the default style, this opens when first visiting the site, user selects corporate style, they open another page in the site - the canvas style shows for a split second, then the corporate style loads over it. Worse on older computers, but on my main computer this does not often happen on Firefox, although on other browsers, especially Chrome its very noticeable. Does anyone have the expertise to update the workings below with a tweak to say, first check for the cookie, then if no cookie, apply the default style, rather than applying the default style seemingly at the same time?
the code I am using is here below:
in html head:
<script type="text/javascript">
$(function()
{
// Call stylesheet init so that all stylesheet changing functions
// will work.
$.stylesheetInit();
// This code loops through the stylesheets when you click the link with
// an ID of "toggler" below.
$('#toggler').bind(
'click',
function(e)
{
$.switcher();
return false;
}
);
// When one of the styleswitch links is clicked then switch the stylesheet to
// the one matching the value of that links rel attribute.
$('.styleswitch').bind(
'click',
function(e)
{
$.stylesheetSwitch(this.getAttribute('rel'));
return false;
}
);
}
);
</script>
<link rel="stylesheet" type="text/css" href="/css/canvas.css " title="canvas">
<link rel="alternate stylesheet" type="text/css" href="/css/corporate.css " title="corporate">
<link rel="alternate stylesheet" type="text/css" href="/css/earth.css " title="earth">
<link rel="alternate stylesheet" type="text/css" href="/css/space-and-stars.css " title="space-and-stars">
<link rel="alternate stylesheet" type="text/css" href="/css/under-the-sea.css " title="under-the-sea">
<link rel="alternate stylesheet" type="text/css" href="/css/classical.css " title="classical">
<link rel="alternate stylesheet" type="text/css" href="/css/creative.css " title="creative">
the JS
(function($)
{
// Local vars for toggle
var availableStylesheets = [];
var activeStylesheetIndex = 0;
// To loop through available stylesheets
$.switcher = function()
{
activeStylesheetIndex ++;
activeStylesheetIndex %= availableStylesheets.length;
$.stylesheetSwitch(availableStylesheets[activeStylesheetIndex]);
};
// To switch to a specific named stylesheet
$.stylesheetSwitch = function(styleName)
{
$('link[#rel*=style][title]').each(
function(i)
{
this.disabled = true;
if (this.getAttribute('title') == styleName) {
this.disabled = false;
activeStylesheetIndex = i;
}
}
);
createCookie('style', styleName, 365);
};
// To initialise the stylesheet with it's
$.stylesheetInit = function()
{
$('link[rel*=style][title]').each(
function(i)
{
availableStylesheets.push(this.getAttribute('title'));
}
);
var c = readCookie('style');
if (c) {
$.stylesheetSwitch(c);
}
};
}
)(jQuery);
// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name)
{
createCookie(name,"",-1);
}
// /cookie functions
I would do it server-side...
Anyway, when you do
$(function()
{
});
jQuery waits until the DOM is fully load to execute the function.
So, you should place the javascript just below the <link />s section, outside $(function(){}); . This will make the script as soon as the browsers parses it, and before the page is fully loaded. (it has to be below the elements because they must be loaded)
I think you might wish to run your code before the DOM is ready. Perhaps you could run it immediately rather than using $(function(){...}), since jQuery waits until the page loads to execute anything in that (hence the flicker).
Also perhaps this might give insight.
http://forum.jquery.com/topic/use-jquery-before-the-dom-is-ready-12-1-2010
Debugging steps for why links are not working:
>>> $('link[#rel*=style][title]') --> seems to show your styles are there
[..., <link rel=​"alternate stylesheet" type=​"text/​css" href=​"/​css/​corporate.css " title=​"corporate">, ...]
>>> $.stylesheetSwitch('corporate') --> seems to work
The only problem is that the links are not having anything bound to the onclick; wait... don't you mean this.getAttribute('title')? as you can see above, rel="alternate stylesheet" which is probably not your intent to use as a unique theme identifier.

Categories