I have 5 scripts on my page and I’d like to add them altogther but am not too sure how.
The first is
<script type="text/javascript"><!--//--><![CDATA[//><!--
sfHover = function() {
var sfEls = document.getElementById("nav").getElementsByTagName("LI");
for (var i=0; i<sfEls.length; i++) {
sfEls[i].onmouseover=function() {
this.className+=" sfhover";
}
sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
}
}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
//--><!]]>
</script>
With the below since I've added the stock control message change, the reload doesn’t work. I’ve added a no conflict script but I don't think I've added it correctly. I'd like to put all 5 scripts together (above and below) in one tag that works - can anyone help out?
<script language="JavaScript">
//
function ImageLoadFailed() {
window.event.srcElement.style.display = "None";
}
// reload after adding product
function AddProductExtras(){
document.location.reload(true);
}
// for stock control - change message
function AddProductExtras(catalogId,productId,ret) {
var td = document.getElementById('catProdTd_'+productId);
if (td.innerHTML == 'This product is unavailable or out of stock.')
td.innerHTML = 'Product added successfully.';
}
jQuery.noConflict();
</script>
create one js file and in that paste all your 5 script codes.
And include this javascript file on your index page as:
<script type="text/javascript" src="name.js"></script>
try to call it in a new js page and link it to your main page.
<script type="text/javascript" src="file.js"></script>
Related
I know this has been covered extensively as separate issues; I've tried copying verified answers, but I'm having trouble homologating Javascript conditional statements and a link URL change.
Essentially, what I need to do is detect mobile users and change a conference call URL to a tel link. I've been using if (screen.width <=699) { as the condition and it works on redirects. Here's what I've tried:
<script type="text/javascript">
<!--
var call=document.getElementByID('phone');
if (screen.width <= 699) {
call.write('<a href="tel:!PHONENUMBER!">');
else
call.write('<a href="!URL!" target="blank">);
}
//--!>
</script>
</head><body>
...
...
I've also tried these with corresponding else statements to no avail:
no var and document.getElementByID('phone').write
onclick = function() { window.location.href ='tel:!PHONENUMBER!};.
call.src.replace('tel:!PHONENUMBER!');
call.setAttribute("href",'tel:!PHONENUMBER!');
I apologize if this is a super basic issue - I'm still learning Javascript. Thank you in advance.
Will
You need to either wait for the page to finish loading before you execute your JavaScript or move your script block to the bottom of the HTML.
If you want to wait for the page to finish loading, then wrap your code in the following:
window.onload = function () {
// your code goes here
}
Figured it out with help from #sepbot.
<body onload="mobileURL()">
<div id="phone"></div>
<script type="text/javascript">
function mobileURL() {
var a = document.createElement("a");
a.innerHTML="!LINKTEXT!";
var myPhone = document.getElementById('phone');
if (screen.width <= 699) {
a.setAttribute('href', '!TELEPHONE!');
myPhone.appendChild(a);
} else {
a.setAttribute('href', '!URL!');
myPhone.appendChild(a);
}
}
</script>
I have the below code is working as long as I load the employee section and its scripts as part of the index.html
index.html Working Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Employee Details loaded as usual and sript is executing able to see alert</h1>
</body>
</html>
Script.js
var empModule = (function (empModule) {
var Years = null;
$(document).ready(function () {
var empdata = { Name: 'Billa' }
var myVM = new empModule.viewModel(empdata);
});
empModule.viewModel = function (data) {
var that = this;
that.Name = data.Name;
alert(that.Name);
};
return {
empModule: empModule
}
} (empModule || {}));
Error Scenario:
We decide to move employee related section based on some condition. Hence we are loading this section and section related script(emp.js) via Ajax. But now it is throwing the error empModule.viewModel is not a constructor. Why is it so?
If I move the document.ready section at the bottom like the below order, it is working
Emp.js(moved from script.js to emp.js and load via ajax(
var empModule = (function (empModule) {
var Years = null;
// Code not working when we load this script file using Ajax.
// But works if we move this document.ready at bottom
//$(document).ready(function () {
// var empdata = { Name: 'Billa' }
// var myVM = new empModule.viewModel(empdata);
//});
empModule.viewModel = function (data) {
var that = this;
that.Name = data.Name;
alert(that.Name);
};
//Working only if I keep the ready section here
$(document).ready(function () {
var empdata = { Name: 'Billa' }
var myVM = new empModule.viewModel(empdata);
});
return {
empModule: empModule
}
} (empModule || {}));
The function empModule will get executed automatically as it is self
executing function. When it is executing it needs to prepare a
empModule.viewModel object, but failed to do that when viewModel
definition is located after document.ready (caller). This happens only
when I load this script via Ajax, but works if I pre load it in a page
This is because in the first example the script.js is part of the document and therefore the document.ready waits for that .js file to be loaded before trying to call empModule.viewModel().
In the second example, your script is loaded asyncronously, but the page is not taking this into account. So the page loads (without the script.js) and then you load the script.
At this point, the document is ready (as the ajax loaded script isn't part of the document) so the empModule.viewModel() call fires straight away, before the rest of the script (which is the bit that defines the function) and you get your error.
Just like #dougajmcdonald said is your issue, but your solution is, instead of loadding by AJAX, just insert the script tag in your document:
// Instead of $.ajax(... /myScript.js) use:
function loadMyScript(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'myScript.js';
script.onload = function() {
empModule.doSomething(); // or callback
};
}
I'm making a website where I'm opening a new window every 30 seconds. I got it to open the new windows properly, but I would like it to close the last window opened before opening the new one, so only one window is open at a time. How would I do this? Here's my code so far:
<script type="text/javascript">
function open_win() {
window.open("http://www.wol.com");
setTimeout(window.open('http://www.bol.com'),35000);
setTimeout(window.open('http://lol.com'),70000);
setTimeout(window.open('http://col.com'),105000);
}
</script>
You can close a window opened by calling window.close on window.open's return value. So:
<script type="text/javascript">
function open_win() {
var wol,bol,lol;
wol=window.open("http://www.wol.com");
setTimeout(function(){window.close(wol);bol=window.open('http://www.bol.com')},35000);
setTimeout(function(){window.close(bol);lol=window.open('http://lol.com')},70000);
setTimeout(function(){window.close(lol);window.open('http://col.com')},105000);
}
</script>
Here a small interval loop for calling urls. Feel free to add an array for different URLS.
<script type="text/javascript">
var lastWindow = "";
setInterval(function(){
if(lastWindow != ""){ lastWindow.close(); }
lastWindow = window.open("url");
}, 30000);
</script>
You can use a string array to store all of the links, and then iterate through that loop calling open and close after 30 seconds. Using a loop and abstracting open/close allows you to have as many links as you'd like.
var linkArray = ['http://www.wol.com', 'http://www.bol.com', 'http://lol.com', ['http://col.com']
function openWin(link) {
var currentWindow = window.open(link);
setTimeout(currentWindow.close(), 30000);
}
function runLinks() {
for(var i = 0; i< linkArray.length; i++) {
openWin(linkArray[i]);
}
}
I've spent the last few hours trying to find the answer to this, but nothing seems to work...
I need to execute a piece of code when a div (or anything inside of it; including iframe content) is clicked. The following code should do it (when added into the div tag), but it doesn't seem to work.
onclick="if(typeof(_vis_opt_top_initialize) =='function'){ _vis_opt_goal_conversion(200); _vis_opt_pause(500);}"
The purpose is to execute a custom conversion goal:
<script type="text/javascript">
if(typeof(_vis_opt_top_initialize) == "function") {
_vis_opt_goal_conversion(200);
}
</script>
Any help will be greatly appreciated :)
I hate using inline js... hate it...
If you need to account for IE (<8), then you can't use addEventListener, so you can do something like this:
function bindListener(el,eventName,eventHandler) {
if (el.addEventListener) { // Anything but IE <8
el.addEventListener(eventName,eventHandler,false);
} else if (el.attachEvent) { // For IE <8
el.attachEvent('on'+eventName,eventHandler);
}
}
Then you can call it using something like this:
var ele = document.getElementById('idOfElement');
bindListener(ele, 'click', functionToCall);
Try using addEventListener. Link here. The Example on that page is exactly what you are asking for.
First give your div a unique ID
<div id="yourDivID"></div>
then set the onclick function in window.onload
var yourDiv = document.getElementById("yourDivID");
yourDiv.onclick = function() {
if(typeof(_vis_opt_top_initialize) == "function") {
_vis_opt_goal_conversion(200);
}
}
}
I write simple example for you:(j Query answer)
Html Code
<div class="test">Click</div>
JavaScript Code
$('div.test').click(function(){
alert("some");
});
Demo
Edited
JavaScript example
<html >
<script type="text/javascript">
function AttachAllDivEvents()
{
var divCollection = document.getElementsByTagName("div");
for (var i=0; i<divCollection.length; i++)
{
AttachDivClickEvent(divCollection[i]);
}
}
function AttachDivClickEvent(divObj)
{
divObj.onclick = function()
{
document.getElementById("count").innerHTML = parseInt(document.getElementById("count").innerHTML) + 1;
};
}
window.onload = AttachAllDivEvents;
</script>
<body>
<div>click</div>
<p id="count" style="font:bold 20px Times;color:red;text-indent:20px">1</p>
</body>
</html>
I am not experienced with Javascript coding. However, I am willing to learn.
I came across some tutorials for creating collapse/expand <div> blocks. I have tested the code with jsfiddle. You can check the code here
It works fine, disregard the styling.
However I can't figure out why the code doesn't work on the live website.
At first I have inserted all the code javascript and HTML in the WordPress Page editor. Then , I moved the javascript in the header. I saw something about the source of the code. I am not sure which is the source.
Here is the javascript code inserted in the header.php:
<script type="text/javascript" language="javascript" src="http://example.com/wp-content/themes/crimson/scripts/jquery.min.js">
function toggle2(showHideDiv, switchTextDiv) {
var ele = document.getElementById(showHideDiv);
var text = document.getElementById(switchTextDiv);
if (ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "expand";
}
else {
ele.style.display = "block";
text.innerHTML = "collapse";
}
}
function toggle3(contentDiv, controlDiv) {
if (contentDiv.constructor == Array) {
for (i = 0; i < contentDiv.length; i++) {
toggle2(contentDiv[i], controlDiv[i]);
}
}
else {
toggle2(contentDiv, controlDiv);
}
}
</script>
The HTML code is the same as on the fiddle HTML panel and it I display in a WordPress page.
Please tell me what wrong with this code? Is it the source of the javascript code?
Chrome console gives me the following:
Uncaught ReferenceError: toggle2 is not defined example.com:103
onclick
The big question is why the code works fine on jsfiddle either on mootools or jquery frameworks, and it doesn't work on the live site?
UPDATE:
I have updated the script tags. Still doesn't work.
You need to put your Javascript code in its own tags.
<script type="text/javascript" language="javascript" src="http://example.com/wp-content/themes/crimson/scripts/jquery.min.js">
<script type="text/javascript">
YOUR CODE HERE
</script>
Also, since you are using jQuery you need to use the ready() function like this:
$(function(){
YOUR CODE HERE
});
Click
<div id="d1">Some content to hide</div>
In the head:
<script type="text/javascript">
$(document).ready(function(){
$("#clickme").toggle(function(){
$("#d1").show();
},
function(){
$("#d1").hide();
}
);
});
</script>
And of course, leave the reference to jQuery in the code.
You have some problems:
An overlaping script tag
You are using Mootools in your Jsfiddle, and jQuery in this sample
You include jquery, but then do the animation in plain Javascript
Try this, correcting the script tags:
<script type="text/javascript" language="javascript" src="http://example.com/wp-content/themes/crimson/scripts/jquery.min.js"></script>
<script type="text/javascript">
function toggle2(showHideDiv, switchTextDiv) {
var ele = document.getElementById(showHideDiv);
var text = document.getElementById(switchTextDiv);
if (ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "expand";
}
else {
ele.style.display = "block";
text.innerHTML = "collapse";
}
}
function toggle3(contentDiv, controlDiv) {
if (contentDiv.constructor == Array) {
for (i = 0; i < contentDiv.length; i++) {
toggle2(contentDiv[i], controlDiv[i]);
}
}
else {
toggle2(contentDiv, controlDiv);
}
}
</script>