I've looked around a lot, and can't seem to find anything that's simple enough for me to do...
I've set up a web page that detects which browser is currently running, and if it's something other than Firefox 4.0, it displays a hidden div that gives a warning stating that the page is best viewed in Firefox 4.0 or greater. Within that div is a button that hides the div onclick.
I'm looking for a way to remember that this button has been clicked during a session, so that when a user clicks on my "home" page, they don't get the same message every time.
Current code:
<head>
<script src="js/browsercheck.js"></script>
<script type="text/javascript">
// external script "browsercheck.js" checks
// which browser/version is being used
// check browser and display message if != Firefox 4.0 or >
function checkBrowser() {
var browser = BrowserDetect.browser;
var version = BrowserDetect.version;
if (browser == "Firefox") {
if (version >= 4) {
// do nothing
}
} else {
document.getElementById("coverall").style.visibility="visible";
document.getElementById("browser").innerHTML = browser + " " + version;
}
}
// remove overlay if user commands
function removeCoverall() {
document.getElementById("coverall").style.visibility="hidden";
}
</script>
</head>
<body>
<div id="coverall" style="visibility:hidden;">
<p>I see you're using <span id="browser"></span>. Please use Firefox.</p>
<button type="button" onclick="removeCoverall()">I understand</button>
</div>
</body>
Using jQuery and the cookie plugin, you can do:
function removeCoverall() {
$.cookie("user_clicked_ok", "true");
document.getElementById("coverall").style.visibility="hidden";
}
$(window).ready(function() {
if ($.cookie("user_clicked_ok")=="true") {removeCoverall();}
});
More details at: http://www.electrictoolbox.com/jquery-cookies/
In the removeCoverall function you could set a cookie which indicates that the user closed the div and in checkBrowser function verify if the cookie is present before showing the div.
You seem to have the right idea, you need cookies! YUM!
JS
function removeCoverall() {
var date = new Date();
date.setTime(date.getTime()+(7*24*60*60*1000));// expires in one week
document.cookie = 'skipNotify=1;expires='+date.toGMTString()+'; path=/';
document.getElementById("coverall").style.visibility="hidden";
}
Now retrieving the cookie can be difficult in javascript, but you can use PHP!
PHP
function checkBrowser() {
<?php if(isset($_COOKIE['skipNotify']))echo'return;';?>
var browser = BrowserDetect.browser;
var version = BrowserDetect.version;
if (browser == "Firefox") {
if (version >= 4) {
// do nothing
}
} else {
document.getElementById("coverall").style.visibility="visible";
document.getElementById("browser").innerHTML = browser + " " + version;
}
}
The above code injects a return statement if the user has the cookie, so the call to the function won't do anything.
As mentioned in the other posts, I highly recommend you use jQuery for all your javascript needs. It's very popular, stable and useful! I only gave my answer as it does not use any third party solution.
Related
i found this code on stackoverflow for a website translation but when i use it, the website flickers like it is going to the same/or other page every millisecond.
I am using this script :
<head>
<script type="text/javascript" src="script/jquery.js"></script>
<script type="text/javascript" src="script/jquery.cookie.js"></script>
<script>
$(function () {
var url = 'http://www.gester.nl';
var english_page = 'index-eng';
var dutch_page = 'index';
if ($.cookie('default_page') != null) {
if (window.location.href != url + '/' + $.cookie('default_page')) {
window.location.href = url + '/' + $.cookie('default_page');
}
}
$('#english').click(function () {
$.cookie('default_page', dutch_page, { expires: 999 });
alert('Dutch was set as the default language');
});
$('#dutch').click(function () {
$.cookie('default_page', dutch_page, { expires: 999 });
alert('Dutch was set as the default language');
});
});</script> </head>
i am using this code for my image button:
<img id="dutch" src="images/dutch.png">
and
<img id="english" src="images/english.png">
I left the website like this so you can test it on my friends website www.gester.nl.
Click back on forth on english button and then again on the dutch button.
Sometimes it works when you click on english and sometimes it doesnt when you click on the english and dutch button.
I really appreciate the help. Cause i was happy when it worked like for seconds and then i saw this problem that i couldn't fix now. Been looking and changing (default_page) and deleting some lines to look where the problem starts but i don't know how to work with this jquery code.
Thanks for your time.
$('#english').click(function () {
$.cookie('default_page', dutch_page, { expires: 999 });
alert('Dutch was set as the default language');
});
You're making it so no matter what that whenever you click Dutch or English, it'll set it to the dutch page still. Therefore, your default page cookie is trying to update to a new variable and it's continuously calling the old one. Try setting the English function to this:
$('#english').click(function () {
$.cookie('default_page', english_page, { expires: 999 });
alert('English was set as the default language');
});
Could be wrong, but I'm just curious as to what that does. Pretty sure that could be causing something though.
With my answer above, also do this.
In your script.js file, change this:
document.getElementById("mybtn").addEventListener("click", function(){
document.getElementById("my_form").className="submitted";
});
To this:
document.getElementById("mybtn").addEventListener("click", function()){
document.getElementById("my_form").className="submitted";
});
I'm trying to insert a cookie that is provided by a video host that will resume a video where the user left off. They have an example that obviously works. When trying to insert this into my Drupal site, the cookie won't work. The video just starts back at the beginning.
I have enabled "PHP input filter", as I read that I needed to do that for drupal to insert the script. Please see the code that is in my node below.
Can anyone help me figure out why this isn't working, how to get it to work, or a better way of doing this with Drupal?
Thank you,
<script type="text/javascript">
wistiaEmbed.ready( function() {
var all_cookies = document.cookie.split(';'), // gets the value of the cookies on the page
cookie_str = "resume_video=",
resume_cookie = does_resume_cookie_exist(all_cookies);
function does_resume_cookie_exist(cookie_arr) {
var i, curr_string, found;
for (i = 0; i < cookie_arr.length; i++) {
curr_string = cookie_arr[i];
if (curr_string.substring(0,5) === cookie_str.substring(0,5)) {
// we've found it!
found = curr_string;
break;
}
}
return found;
}
function set_cookie_time(t) {
document.cookie = cookie_str + t.toString(); // this takes the time (t) and sets the cookie with that time
}
if (resume_cookie) {
num = resume_cookie.split('=')[1];
start_time = parseInt(num);
wistiaEmbed.time(start_time).play(); // plays the video at the specific time defined in the cookie upon return to the page
} else {
set_cookie_time(0); // places a cookie on the visitor
wistiaEmbed.play(); // starts the video from the beginning
}
wistiaEmbed.bind("timechange", function(t) { // on timechange, reset cookie
set_cookie_time(t);
});
wistiaEmbed.bind("end", function() { // if person has watched the entire video, sets the video to beginning upon retun
set_cookie_time(0);
});
});
</script>
<div id="wistia_npcc5k96s9" class="wistia_embed" style="width:640px;height:508px;"> </div>
<script charset="ISO-8859-1" src="http://fast.wistia.com/assets/external/E-v1.js"> </script>
<script>
wistiaEmbed = Wistia.embed("npcc5k96s9");
</script>**strong text**
What version of drupal are you using? Does the code that you gave actually output in your request response?
There are several solutions to this (IMO).
If the code is showing up in the response, it could be some other javascript error that preventing your code from executing.
If that snippet of code is applicable to all nodes of that type you can use the node_view hook in order to inject your code on that node type, for example (I am assuming D7):
function mymodule_node_view($node, $view_mode)
{
if($node->type =='video_page')
{
drupal_add_js('resume_video.js'); // this js holds your code snippet
}
}
Here's a reference that could help you out
https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7
You can similarly inject that snippet of code at the theme layer using a theme hook, probably hook_preprocess https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess/7
Hope that helps.
I have been trying to get SimpleModal Age Verification page to popup on the first visit to my site. Meaning if the previous site wasn't me display popup. The code below is what I have so far. Basically the issue is that I am getting the popup once in a while for no reason when I click a link. I can't find a rhyme or reason too it. I have had a lot of help from the people here with this code. I'll get a little further then a problem pops up, then i'll fix that and another one pops up. I hope I'm getting pretty close here. ;)
Thanks guys!
<div class="age" id="verify">
<div><img src="/image/white.png"></img></div>
<div id="noman">ARE YOU OVER 18?</div>
<div>
<p> If not, leave now and we wont tell your mom.
</br> By continuing you agree you are 18 or older.
</p>
</div>
<div id="YN">
Yes
No
</div>
</div>
<script>
$(document).ready(function(){
if ( document.referrer == null || document.referrer.indexOf(window.location.hostname) < 0 ) {
$("#verify").modal({opacity:85, position: ["20%",""], onOpen: function (dialog) {
dialog.overlay.fadeIn('slow', function () {
dialog.container.slideDown('slow', function () {
dialog.data.fadeIn('slow');
return false;
});
});
}});
}
});
</script>
<script type="text/javascript" >
function redirect(url) {
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
var referLink = document.createElement('a');
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
} else {
location.href = url;
}
}
</script>
The problem is that you use document.referrer, but its use should be avoided.
For example, I have disabled it using Firefox's about:config page.
Or even if enabled, it doesn't work with window.open.
Then, better use something like sessionStorage (or localStorage).
I am using jQuery BlockUI for opening a new webpage that takes some time due to a lot of database querying with the following javascript:
function productSheet(url2) {
$.blockUI.defaults.overlayCSS = {};
$.blockUI({ });
$.ajax({
url: url2,
success: function (respones) {
var win = window.open();
with (win.document) {
open();
write(respones);
close();
}
}
});
};
At the new page i got some jQuery JavaScript and a reference to the external jQuery script. However when i render the page after the JavaScript above all my script throws error for: "$ undefined".
I can refresh the page and everything starts working and I am not getting any script errors.
This problem only occur when I am debugging in IE 9, on Firefox everything works (no JavaScript errors and the script works).
Does anyone have any idea on whats the problem can be?
EDIT:
The page iam rendering is a MVC 3 view. So the script above goes to an MVC action that returns a this view:
#model WebApplication.Controllers.ProductSheetModel
<!DOCTYPE html>
<html>
<head>
<title>Sheet - #Model.ArticleMain.ArticleMain.T0018_BENAM</title>
<script src="../../js/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script>
<link href="../../css/ProductSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
#if (Model.IsPDFExport == false)
{
#Html.DisplayFor(model => model.ArticleMain, "ProductSheetHeader")
}
... some more partical views...
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
var tabelheight1 = $("#divNutritiveValues").height();
var tabelheight2 = $("#divMarking").height();
if (tabelheight1 > tabelheight2) {
$("#divMarking").css("height", tabelheight1 + "px");
$("#divNutritiveValues").css("height", tabelheight1 + "px");
}
if (tabelheight2 > tabelheight1) {
$("#divNutritiveValues").css("height", tabelheight2 + "px");
$("#divMarking").css("height", tabelheight2 + "px");
}
var tableheightStore = $("#divStore").height();
var tableheightCooking = $("#divCooking").height();
if (tableheightCooking > tableheightStore) {
$("#divCooking").css("height", tableheightCooking + "px");
$("#divStore").css("height", tableheightCooking + "px");
}
if (tableheightStore > tableheightCooking) {
$("#divCooking").css("height", tableheightStore + "px");
$("#divStore").css("height", tableheightStore + "px");
}
var tableInfoProvid = $("#divInformationProvider").height();
var tableManufac = $("#divManufacturer").height()
if (tableInfoProvid > tableManufac) {
$("#divManufacturer").css("height", tableInfoProvid + "px");
$("#divInformationProvider").css("height", tableInfoProvid + "px");
}
if (tableManufac > tableInfoProvid) {
$("#divInformationProvider").css("height", tableManufac + "px");
$("#divManufacturer").css("height", tableManufac + "px");
}
});
The problem is that $ is undefined on your page on IE.
Normally, jQuery sets $ as a reference to the jQuery object. See docs.
For some reason, either the $ reference is being removed or is not happening on IE. Can you post more of your code?
One work-around would be to use jQuery instead of $
But it would be good to better understand what is actually happening on IE.
I believe this is caused as your JavaScript registrations are not occurring with your AJAX posts, meaning that they get lost and don't get re-registered.
This is a common issue when working with AJAX, and this article explains it perfectly and provides what you need.
i came up with a solution and want to share it with you. In my site i created a script checking if jquery was undefined.
if (typeof jQuery == 'undefined') {
window.location.reload();
}
after i have reloaded the page again all my scripts work, maybe not the best of solutions but it works so i am happy.
I am using JQuery 1.3.2-min in a project to handle JavaScript animations, ajax, etc. I have stored the file on the same server as the site instead of using Google. When I run the site locally on my development machine, everything works fine in FF, IE, Opera, and Safari (all the latest versions - I work from home and I only have 1 machine for personal use and development use) except for some CSS differences between them and when I go to the live site on my machine it works fine also. I have cleared my caches and hard refreshed the page, and it still works.
This is where it gets interesting however. When I send the site to my boss to test in various OS/Browser configurations, one page doesn't work correctly, some of it works, some doesn't. Also, the client (who uses IE 8) has also confirmed that it is not completely working - in fact he has told me that the page will work fine for a hour, and then just "turn off" for a while. I have never heard of this sort of thing before, and google isn't turning too much up. I have a hunch it may partly be with JQuery's .data(), but I'm not sure.
The page is basically nested unordered lists, and three basic actions happen on the list.
The top most unordered list is set to visible (all list via css are set to display: none to keep them hidden on a fresh page request); all list items divs are given a hover action of full opacity on mouseon, and faded back to 50% opacity on mouseoff; and then whenver a paragraph is clicked, the top most unordered list in that list item is displayed.
Here is my Javascript file for the page:
$(function() {
// Set first level ul visible
$('div#pageListing ul:first').css('display', 'block');
// Disable all the hyperlinks in the list
$('div#pageListing li a').click(function() {
var obj;
obj = $(this).parent(0).parent('div:first');
highlight(obj);
return false;
});
// List Item mouse hovering
$('#pageListing li').hover(
// Mouse On
function() {
if ($(this).children('div').attr('id') !== 'activePage') {
$(this).children('div').css('opacity', 1).css('filter',
'alpha(opacity=100)');
}
}, // Mouse off
function() {
if ($(this).children('div').attr('id') !== 'activePage') {
$(this).children('div').css('opacity', 0.4).css('filter',
'alpha(opacity=40)');
}
});
// Active list item highlighting
$('#pageListing li div').click(function() {
highlight($(this));
});
// Sub-list expanding/collapsing
$('#pageListing p.subpageslink').click(function() {
// Get next list
var subTree = $(this).parent('div').next('ul');
// If list is currently active, close it, else open it.
if (subTree.data('active') != true) {
subTree.data('active', true);
subTree.show(400);
} else {
subTree.data('active', false);
subTree.hide(400);
}
});
// Double clicking of list item - edit a page
$('#pageListing li div').dblclick(function() {
var classes = $(this).attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
editPage(pageID);
});
// Handle button clicking
$('button#addPage').click(function() {
addPage();
});
$('button#editPage').click(function() {
var div = $('div#activePage');
var classes = div.attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
editPage(pageID);
});
$('button#delPage').click(function() {
var div = $('div#activePage')
var classes = div.attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
delPage(pageID);
});
});
// Highlighting of page when clicked
function highlight(obj) {
// Get previous hightlighted element
// and un-highlight
var oldElement = $('div#activePage');
oldElement.css('background', 'white');
oldElement.css('opacity', 0.4).css('filter', 'alpha(opacity=40)');
oldElement.removeAttr('id');
// highlight current selection
obj.attr('id', 'activePage');
obj.css('opacity', 1).css('filter', 'alpha(opacity=100)');
obj.css('background', '#9dc0f4');
// add appropiate action buttons
$('button.pageButton').css('display', 'inline');
}
function addPage() {
window.location = "index.php?rt=cms/editPage";
}
function delPage(page) {
var confirm = window.confirm("Are you sure? Any sub-pages WILL BE deleted also.");
if (confirm) {
var url = './components/cms/controller/forms/deletePage.php';
$.ajax( {
url : url,
type : 'GET',
data : 'id=' + page,
success : function(result) {
if (!result) {
document.location = "index.php?rt=cms";
} else {
window.alert('There was a problem deleting the page');
}
}
});
}
}
function editPage(page) {
var url = "index.php?rt=cms/editPage/" + page;
window.location = url;
}
Is it possible that you are linking to (some of) the script files using a src that points to a file on your local disk/HDD? If so, that would explain why it works only on your machine, as then only your machine has access to the script file.
Thank you one and all for your suggestions. The end problem was miscommunication. I work from home, and upload my projects to a SVN server, which the boss then uses to update the live server. Somehow, the correct files were not getting updated - a communication error on my part. Another possible reason was that the page, while being declared XHTML 1.0 Strict, had something like 50 validation errors (mosting incorrectly nested UL), and I cleaned that up to 5 errors. So thank you all, but again a sad example of the importance of team work communication.