the community!
I'm going through some issues. the redirection feature doesn't work well when I try to post the link on the Facebook platform. in general, the redirection only works outside facebook community. when I click on the shared link on Facebook automatically set this parameter at the end of URL ?fbclid=
example : https://myblog.blogspot.com/go/fb?fbclid=
but when I put the link directly on the browser works properly
here is my code
<script language='javascript'>
//<![CDATA[
var key = window.location.href.split("go/")[1].replace("/","")
var urls={
'fb':'https://www.facebook.com',
}
if(key){
if(urls[key]){
window.location.href=urls[key]
}else{
document.write("'"+key+"' not found 😞");
}
}
//]]>
</script>
Use window.location.pathname instead of window.location.href.
<script>
//<![CDATA[
var key = window.location.pathname.split("go/")[1].replace("/","")
var urls={
'fb':'https://www.facebook.com',
}
if(key){
if(urls[key]){
window.location.href=urls[key]
} else {
document.write("'"+key+"' not found 😞");
}
}
//]]>
</script>
I am a fairly new programmer, and currently am trying to understand OOP from the JS side of things. I have some pretty basic code for a flashing cursor, yet for some reason it isnt working. The page loads, and the cursor just appears onscreen with no changing. The code is below:
<html>
<head>
<title>Cursor</title>
<script src="jquery.js"></script>
<script>
var str = null;
var counter = 0;
var flipFlop = function() {
alert("working");
if(counter === 0) {
document.getElementbyId('console').style.visibility='visible';
counter = 1;
}
else if(counter === 1) {
document.getElementbyId('console').style.visibility='hidden';
counter = 0;
}
else {
//debug alert
alert("function broken.");
}
};
var setIntOnload = function() {
setInterval(function() {
flipFlop();
}, 1000);
};
</script>
</head>
<body onload="setIntOnload()">
<div id="console">
|
</div>
</body>
</html>
Not sure why this isnt working... Help would be appreciated :)
PS First Post :D
Its Working
Change getElementById instead of getElementbyId
Fiddle
You have a typo in your code. Use getElementById instead of getElementbyId. JavaScript variable names (and methods) are case sensitive.
Fiddle: http://jsfiddle.net/FcrQ7/
Always check your browser console in case something in your code is not working. You had the following error:
Uncaught TypeError: Object # has no method 'getElementbyId'
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 have read a lot of topics and tried a lot of stuff but I can't get what I want.
I just moved my js code at the end of the page and now I get some errors.
This is how my page looks like:
<html>
<head>
bla bla
</head>
<body>
bla bla
<div class="advertising">
<script type="text/javascript" defer="defer">
window.onload = adsense();
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<script language="javascript" type="text/javascript" src="fonctions.js"></script>
</body>
</html>
In fonctions.js I have my google adsense code:
function adsense(){
<!--
google_ad_client = "pub-xxxxx";
/* 120x600, date de création 11/06/11 */
google_ad_slot = "xxxxx";
google_ad_width = 120;
google_ad_height = 600;
//-->
}
The idea was to have the same code for adsense at only one place but I can't get it to load after the file fonctions.js
I tried defer="defer", window.onload ...
Any ideas?
Thanks
I get this error in Firebug:
Error : adsense is not defined
PS: I would like to avoid to use Jquery (to avoid making pages too big)
UPDATE:
<script type="text/javascript" defer="defer">
(function() { // 'sandbox' javascript pattern to prevent clobbering
// global namespace
var executeProxy = function() {
if (typeof adsense === 'function') { // adsense is configured
adsense();
} else { // adsense is not configured;
// therefore, try again later
setTimeout(executeProxy, 50);
}
};
executeProxy();
}());
</script>
<script language="javascript" type="text/javascript" src="fonctions.js"></script>
in fonctions.js if I put the following code, the "ok" is displayed:
function adsense(){
alert ("ok");
}
However if I have this code, the ad is not displayed:
function adsense(){
google_ad_client = "pub-xx";
/* 120x600, date de création 16/04/11 */
google_ad_slot = "xxx";
google_ad_width = 120;
google_ad_height = 600;
}
My guess is that it's a Google issue... The code cannot be loaded in this way...?
If I put the adsense code in the page (below the call - where you do alert('here'); ) it is well displayed... So my adsense code is correct
UPDATE:
I have finally changed the solution, I've put the code in a .html file and I include it using php. So it's not in my js file anymore.
Thanks for your help anyway.
window.onload expects a function callback; however, you are executing adsense with adsense(), and adsense doesn't return a function; therefore, window.onload will discard that. Change to:
window.onload = adsense;
UPDATE
The above answer should be discarded, but I'm leaving it up so that people can know that window.onload expects a function callback :)
Keep in mind that defer on the script element will instruct the browser to wait until the page has been loaded to execute the script; however, your fonctions.js is in the src attribute of your last script tag; therefore, your deferred script will most likely execute before adsense has been defined, because the browser will make an http request to retrieve your script. This will allow deferred scripts to continue executing while adsense is not defined. Try this in place of your original deferred script:
<script type="text/javascript" defer="defer">
(function() { // 'sandbox' javascript pattern to prevent clobbering
// global namespace
var executeProxy = function() {
if (typeof adsense === 'function') { // adsense is configured
adsense();
} else { // adsense is not configured;
// therefore, try again later
setTimeout(executeProxy, 50);
}
};
executeProxy();
}());
</script>
UPDATE
I forgot that script defer is not supported in anything outside of IE. Therefore, the deferring issue should not be at play here; however, I tested the following code in FF and Chrome, and it works:
<script type="text/javascript" defer="defer">
(function() { // 'sandbox' javascript pattern to prevent clobbering
// global namespace
var executeProxy = function() {
if (typeof adsense === 'function') { // adsense is configured
adsense();
} else { // adsense is not configured;
// therefore, try again later
setTimeout(executeProxy, 50);
}
};
executeProxy();
}());
</script>
<script type="text/javascript">
function adsense() {
alert('here');
}
</script>
window.onload = adsense(); calls adsense() immediately and assigns its return value to onload.
I would like to implement a JavaScript code which states this:
if the page is loaded completely, refresh the page immediately, but only once.
I'm stuck at the "only once":
window.onload = function () {window.location.reload()}
this gives a loop without the "only once". jQuery is loaded if this helps.
I'd say use hash, like this:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
When I meet this problem, I search to here but most of answers are trying to modify existing url. Here is another answer which works for me using localStorage.
<script type='text/javascript'>
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
</script>
<script type="text/javascript">
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
</script>
Due to the if condition the page will reload only once.I faced this problem too and when I search ,I found this nice solution.
This works for me fine.
Check this Link it contains a java-script code that you can use to refresh your page only once
http://www.hotscripts.com/forums/javascript/4460-how-do-i-have-page-automatically-refesh-only-once.html
There are more than one way to refresh your page:
solution1:
To refresh a page once each time it opens use:
<head>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>
sollution2:
<script language=" JavaScript" >
<!--
function LoadOnce()
{
window.location.reload();
}
//-->
</script>
Then change your to say
<Body onLoad=" LoadOnce()" >
solution3:
response.setIntHeader("Refresh", 1);
But this solution will refresh the page more than one time depend on the time you specifying
I hope that will help you
<script>
function reloadIt() {
if (window.location.href.substr(-2) !== "?r") {
window.location = window.location.href + "?r";
}
}
setTimeout('reloadIt()', 1000)();
</script>
this works perfectly
Finally, I got a solution for reloading page once after two months research.
It works fine on my clientside JS project.
I wrote a function that below reloading page only once.
1) First getting browser domloading time
2) Get current timestamp
3) Browser domloading time + 10 seconds
4) If Browser domloading time + 10 seconds bigger than current now timestamp then page is able to be refreshed via "reloadPage();"
But if it's not bigger than 10 seconds that means page is just reloaded thus It will not be reloaded repeatedly.
5) Therefore if you call "reloadPage();" function in somewhere in your js file page will only be reloaded once.
Hope that helps somebody
// Reload Page Function //
function reloadPage() {
var currentDocumentTimestamp = new Date(performance.timing.domLoading).getTime();
// Current Time //
var now = Date.now();
// Total Process Lenght as Minutes //
var tenSec = 10 * 1000;
// End Time of Process //
var plusTenSec = currentDocumentTimestamp + tenSec;
if (now > plusTenSec) {
location.reload();
}
}
// You can call it in somewhere //
reloadPage();
i put this inside my head tags of the page i want a single reload on:
<?php if(!isset($_GET['mc'])) {
echo '<meta http-equiv="refresh" content= "0;URL=?mc=mobile" />';
} ?>
the value "mc" can be set to whatever you want, but both must match in the 2 lines. and the "=mobile" can be "=anythingyouwant" it just needs a value to stop the refresh.
Use window.localStorage... like this:
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
It works for me.
After </body> tag:
<script type="text/javascript">
if (location.href.indexOf('reload')==-1)
{
location.href=location.href+'?reload';
}
</script>
You can make one verable once = false then reload your page with if else like if once == false reload page an make once true.
You'd need to use either GET or POST information. GET would be simplest. Your JS would check the URL, if a certain param wasn't found, it wouldn't just refresh the page, but rather send the user to a "different" url, which would be the same URL but with the GET parameter in it.
For example:
http://example.com -->will refresh
http://example.com?refresh=no -->won't refresh
If you don't want the messy URL, then I'd include some PHP right at the beginning of the body that echos a hidden value that essentitally says whether the necessary POST param for not refreshing the page was included in the initial page request. Right after that, you'd include some JS to check that value and refresh the page WITH that POST information if necessary.
Try with this
var element = document.getElementById('position');
element.scrollIntoView(true);`
Please try with the code below
var windowWidth = $(window).width();
$(window).resize(function() {
if(windowWidth != $(window).width()){
location.reload();
return;
}
});
Here is another solution with setTimeout, not perfect, but it works:
It requires a parameter in the current url, so just image the current url looks like this:
www.google.com?time=1
The following code make the page reload just once:
// Reload Page Function //
// get the time parameter //
let parameter = new URLSearchParams(window.location.search);
let time = parameter.get("time");
console.log(time)//1
let timeId;
if (time == 1) {
// reload the page after 0 ms //
timeId = setTimeout(() => {
window.location.reload();//
}, 0);
// change the time parameter to 0 //
let currentUrl = new URL(window.location.href);
let param = new URLSearchParams(currentUrl.search);
param.set("time", 0);
// replace the time parameter in url to 0; now it is 0 not 1 //
window.history.replaceState({}, "", `${currentUrl.pathname}?${param}`);
// cancel the setTimeout function after 0 ms //
let currentTime = Date.now();
if (Date.now() - currentTime > 0) {
clearTimeout(timeId);
}
}
The accepted answer uses the least amount of code and is easy to understand. I just provided another solution to this.
Hope this helps others.
React Hook worked for me.
import { useEffect, useState } from 'react';
const [load, setLoad] = useState(false);
window.onload = function pageLoad() {
if (load) {
window.location.reload(true);
setLoad(false);
}
};
nothing work for me perfectly except this, -added to my JavaScript file-:
function LoadOnce() {
if (localStorage.getItem('executed') == 'false') {
window.location.reload()
localStorage.setItem('executed', true)
}
}
setTimeout(function () {
LoadOnce()
}, 100)
and in the previous page I wrote:
localStorage.setItem('executed', false)
I got the Answer from here and modified it.This is the perfect solution for me.
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
setTimeout(function() {
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
}, 1500); // 1500 milliseconds = 1.5 seconds
setTimeout(function() {
localStorage.removeItem('refresh')
}, 1700); // 1700 milliseconds = 1.7 seconds
var foo = true;
if (foo){
window.location.reload(true);
foo = false;
}
use this
<body onload = "if (location.search.length < 1){window.location.reload()}">
Use rel="external"
like below is the example
<li>Home</li>