Run a JS function on page load - javascript

I know that this question has been asked multiple times, but my case is different. So I have an external JavaScript file which contains the code for my accordion menus (you know, the user clicks on a title and it expands). Now I want to get a # (hash sign) from the url and according to it to open a specific "accordion" onload.
So here's what I've tried:
<body onload="runAccordion(index);"> <!-- In the example bellow, index should be equal to 1 -->
But it never worked (as desired), because I don't know how to "read" the url's # (element's id)...
Here's the markup for an accordion:
<div id="AccordionContainer" class="AccordionContainer">
<div onclick="runAccordion(1);">
<div class="AccordionTitle" id="AccordionTitle1">
<p>Title</p>
</div>
</div>
<div id="Accordion1Content" class="AccordionContent">
<p>
<!-- Content -->
</p>
</div>
Or maybe I should use PHP $_GET???
JS file contents:
var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index) {
var nID = "Accordion" + index + "Content";
if (openAccordion == nID)
nID = '';
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId) {
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var opening = (openingId == '') ? null : document.getElementById(openingId);
var closing = (closingId == '') ? null : document.getElementById(closingId);
if (timeLeft <= elapsedTicks) {
if (opening != null)
opening.style.height = ContentHeight + 'px';
if (closing != null) {
closing.style.display = 'none';
closing.style.height = '0px';
}
return;
}
timeLeft -= elapsedTicks;
var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight);
if (opening != null) {
if (opening.style.display != 'block')
opening.style.display = 'block';
opening.style.height = (ContentHeight - newClosedHeight) + 'px';
}
if (closing != null)
closing.style.height = newClosedHeight + 'px';
setTimeout("animate(" + curTick + "," + timeLeft + ",'" + closingId + "','" + openingId + "')", 33);
}

Give the following a try:
$(document).ready(function() {
var hash = window.location.hash;
hash = hash.length > 0 ? hash.substring(1);
if (hash.length) {
runAccordion(window.location.hash);
}
});
The above will grab your hash index out of the URL. To add a hash to the URL, try the following:
window.location.hash = 1; //or whatever your index is

# You can use: #
window.onload = function() {
runAccordion(window.location.hash);
}

Related

jQuery to emulate iPhone password input changes textbox to disabled in a Visual Studio web application

I am working on a web application in Visual Studio using visual basic and master pages. I have 10 textbox fields on a child page where I would like to emulate the iPhone password entry (ie. show the character entered for a short period of time then change that character to a bullet). This is the definition of one of the text box controls:
<asp:TextBox ID="txtMID01" runat="server" Width="200" MaxLength="9"></asp:TextBox>
At the bottom of the page where the above control is defined, I have the following:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="lib/jQuery.dPassword.js"></script>
<script type="text/javascript">
$(function () {
var textbox01 = $("[id$=txtMID01]");
alert(textbox01.attr("id"));
$("[id$=txtMID01]").dPassword()
});
</script>
When the page loads, the alert displays MainContent_txtMID01 which is the ID of the control preceeded with the name of the content place holder.
The following is the contents of lib/jQuery.dPassword.js (which I found on the internet):
(function ($) {
$.fn.dPassword = function (options) {
var defaults = {
interval: 200,
duration: 3000,
replacement: '%u25CF',
// prefix: 'password_',
prefix: 'MainContent_',
debug: false
}
var opts = $.extend(defaults, options);
var checker = new Array();
var timer = new Array();
$(this).each(function () {
if (opts.debug) console.log('init [' + $(this).attr('id') + ']');
// get original password tag values
var name = $(this).attr('name');
var id = $(this).attr('id');
var cssclass = $(this).attr('class');
var style = $(this).attr('style');
var size = $(this).attr('size');
var maxlength = $(this).attr('maxlength');
var disabled = $(this).attr('disabled');
var tabindex = $(this).attr('tabindex');
var accesskey = $(this).attr('accesskey');
var value = $(this).attr('value');
// set timers
checker.push(id);
timer.push(id);
// hide field
$(this).hide();
// add debug span
if (opts.debug) {
$(this).after('<span id="debug_' + opts.prefix + name + '" style="color: #f00;"></span>');
}
// add new text field
$(this).after(' <input name="' + (opts.prefix + name) + '" ' +
'id="' + (opts.prefix + id) + '" ' +
'type="text" ' +
'value="' + value + '" ' +
(cssclass != '' ? 'class="' + cssclass + '"' : '') +
(style != '' ? 'style="' + style + '"' : '') +
(size != '' ? 'size="' + size + '"' : '') +
(maxlength != -1 ? 'maxlength="' + maxlength + '"' : '') +
// (disabled != '' ? 'disabled="' + disabled + '"' : '') +
(tabindex != '' ? 'tabindex="' + tabindex + '"' : '') +
(accesskey != undefined ? 'accesskey="' + accesskey + '"' : '') +
'autocomplete="off" />');
// change label
$('label[for=' + id + ']').attr('for', opts.prefix + id);
// disable tabindex
$(this).attr('tabindex', '');
// disable accesskey
$(this).attr('accesskey', '');
// bind event
$('#' + opts.prefix + id).bind('focus', function (event) {
if (opts.debug) console.log('event: focus [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
checker[getId($(this).attr('id'))] = setTimeout("check('" + getId($(this).attr('id')) + "', '')", opts.interval);
});
$('#' + opts.prefix + id).bind('blur', function (event) {
if (opts.debug) console.log('event: blur [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
});
setTimeout("check('" + id + "', '', true);", opts.interval);
});
getId = function (id) {
var pattern = opts.prefix + '(.*)';
var regex = new RegExp(pattern);
regex.exec(id);
id = RegExp.$1;
return id;
}
setPassword = function (id, str) {
if (opts.debug) console.log('setPassword: [' + id + ']');
var tmp = '';
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == unescape(opts.replacement)) {
tmp = tmp + $('#' + id).val().charAt(i);
}
else {
tmp = tmp + str.charAt(i);
}
}
$('#' + id).val(tmp);
}
check = function (id, oldValue, initialCall) {
if (opts.debug) console.log('check: [' + id + ']');
var bullets = $('#' + opts.prefix + id).val();
if (oldValue != bullets) {
setPassword(id, bullets);
if (bullets.length > 1) {
var tmp = '';
for (i = 0; i < bullets.length - 1; i++) {
tmp = tmp + unescape(opts.replacement);
}
tmp = tmp + bullets.charAt(bullets.length - 1);
$('#' + opts.prefix + id).val(tmp);
}
else {
}
clearTimeout(timer[id]);
timer[id] = setTimeout("convertLastChar('" + id + "')", opts.duration);
}
if (opts.debug) {
$('#debug_' + opts.prefix + id).text($('#' + id).val());
}
if (!initialCall) {
checker[id] = setTimeout("check('" + id + "', '" + $('#' + opts.prefix + id).val() + "', false)", opts.interval);
}
}
convertLastChar = function (id) {
if ($('#' + opts.prefix + id).val() != '') {
var tmp = '';
for (i = 0; i < $('#' + opts.prefix + id).val().length; i++) {
tmp = tmp + unescape(opts.replacement);
}
$('#' + opts.prefix + id).val(tmp);
}
}
};
})(jQuery);
When I execute my code, the code behind populates the value of the textbox with "123456789" and when the page gets rendered, all the characters have been changed to bullets, which is correct. The problem I am having is that the textbox has been disabled so I can not edit the data in the textbox.
I removed (by commenting out) the references to the disabled attribute but the control still gets rendered as disabled.
As a side note, the code that I found on the internet was originally designed to work with a textbox with a type of password but when I set the TextMode to password, not only does the control get rendered as disabled, but the field gets rendered with no value so I left the TextMode as SingleLine.
Any suggestions or assistance is greatly appreciated.
Thanks!
As far as I know, it is not possible to have it so that while you type a password, the last letter is visible for a second and then turns into a bullet or star.
However what you can do is as the user types in password, with a delay of lets say 500ms store the string the user has typed in so far into some variable and replace the content of the password field or the text field with stars or black bullets. This will give you what you are looking for.

jQuery function conversion

I've been working on this script that I am using with a WordPress plugin I wrote for our blogs at work. I'm stripping it down to make it a pure jQuery plugin but most of the questions I've seen where for getting the plugin to work like this:
$('.some-target').cta();
Whereas I want to write it so that the user can do something like:
cta();
or
$.cta
I'm not really getting clear answers or seeing many guides covering this, or really if it's possible. In the end I want it to work like it's original iteration for WP, but as a stand alone jQuery plugin for static sites:
cta({
text: "Some Text",
icon: "Some-icon.jpg",
dist: 50
});
Here is the original code:
jQuery(document).ready(function($){
cta = function(o) {
o = o || {};
var bgColor = o.bgColor;
var url = o.url;
var text = o.text;
var icon = o.icon;
var buttonText = o.buttonText;
var target = o.target;
var dist = o.dist;
if((o.icon != null) || o.icon == "" ) {
jQuery('body').append(
'<div class="cta-popup-wrapper with-icon"><div class="cta-popup"><span class="close-trigger">X</span><img class="cta-icon" src="' + icon + '" alt="Call to Action Icon"><p>' + text + '</p><a class="cta-button" style="background-color:' + bgColor + ';" href="' + url + '">' + buttonText + '</a></div></div>'
);
} else {
jQuery('body').append(
'<div class="cta-popup-wrapper without-icon"><div class="cta-popup"><span class="close-trigger">X</span><p>' + text + '</p><a class="cta-button" style="background-color:' + bgColor + ';" href="' + url + '">' + buttonText + '</a></div></div>'
);
}
if(target != null) {
var t = $(target);
if(t.length) {
$(window).scroll(function() {
var hT = t.offset().top,
hH = t.outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
$('.cta-popup-wrapper').addClass('shown');
} else {
$('.cta-popup-wrapper').removeClass('shown');
}
});
}
} else {
if((dist != null) && (dist > 0)) {
var b = $('body').innerHeight();
dist = dist / 100;
var trigger = b * dist;
$(window).scroll(function() {
var wS = $(this).scrollTop();
if (wS > trigger){
$('.cta-popup-wrapper').addClass('shown');
} else {
$('.cta-popup-wrapper').removeClass('shown');
}
});
}
}
}
});

jQuery use dynamically created ID

I am trying to use dynamically created IDs in javascript function, but it's not working. I thought that prepending # to string id should work, but it's not.
Code:
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("'#" + idCheckBoxToCompare + "'").prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("'#" + textBoxID + "'").val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("'#" + idInputBox + "'").val();
if ($("'#" + idCheckBox + "'").prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("'#" + idCheckBox + "'").prop('checked', false);
}
}
}
}
}
I've tried to build same id as this is:
'#testid'
so usage would be:
$('#testid')
But it's not working. How to use properly dynamically created IDs?
Your code is look complicated with too many " and '. Also Javascript can concat string and number by just use +. No need to convert it to string first. So, I updated it to make it more readable.
Try this
var IterateCheckedDatesAndUncheckWithSameValue = function(elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber;
if ($('#' + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber;
textBoxValue = $('#' + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i;
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i;
inputBoxValue = $('#' + idInputBox).val();
if ($('#' + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$('#' + idCheckBox).prop('checked', false);
}
}
console.log('#' + idCheckBox); //print here just to see the id results
}
}
}
ID in html can be only one element per page. So please make sure that the ID you generate from this method not match with other.
Jquery selector can read String variable.
So you can just do var id = "#test". Then put it like this $(id).
Or
var id = "test"; then $("#"+test).
Use this,
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("#" + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("#" + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("#" + idInputBox).val();
if ($("#" + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("#" + idCheckBox).prop('checked', false);
}
}
}
}
}
I face the same problem using Jquery .Try $(document).getElementbyId('myid'). Hope help.
Edit
Change :
$("#" + idCheckBoxToCompare) by $(document).getElementbyId(idCheckBoxToCompare)

Trigger onClick event with URL

I would like to be able to navigate to a page and open up content in one of three content containers in an accordion js structure.
Here is the html:
<div id="navigation">
<div id="AccordionContainer" class="AccordionContainer">
<div onclick="runAccordion(1); ContentHeight=1040;" id="reel">
<div class="AccordionTitle" onselectstart="return false;">REEL</div>
</div>
<div id="Accordion1Content" class="AccordionContent">
<div id="reelSpots">
content
</div>
</div>
<div onclick="runAccordion(2); ContentHeight=1075;">
<div class="AccordionTitle" onselectstart="return false;">ABOUT</div>
</div>
<div id="Accordion2Content" class="AccordionContent">
content
</div>
<div onclick="runAccordion(3); ContentHeight=175;">
<div class="AccordionTitle" onselectstart="return false;">CONTACT</div>
</div>
<div id="Accordion3Content" class="AccordionContent">
content
</div>
</div>
</div>
And here is my javascript:
// JavaScript Document
var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index)
{
var nID = "Accordion" + index + "Content";
if(openAccordion == nID)
nID = '';
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'"
+ openAccordion + "','" + nID + "')", 33);
openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId)
{
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var opening = (openingId == '') ? null : document.getElementById(openingId);
var closing = (closingId == '') ? null : document.getElementById(closingId);
if(timeLeft <= elapsedTicks)
{
if(opening != null)
opening.style.height = ContentHeight + 'px';
if(closing != null)
{
closing.style.display = 'none';
closing.style.height = '0px';
}
return;
}
timeLeft -= elapsedTicks;
var newClosedHeight = Math.round((timeLeft/TimeToSlide) * ContentHeight);
if(opening != null)
{
if(opening.style.display != 'block')
opening.style.display = 'block';
opening.style.height = (ContentHeight - newClosedHeight) + 'px';
}
if(closing != null)
closing.style.height = newClosedHeight + 'px';
setTimeout("animate(" + curTick + "," + timeLeft + ",'"
+ closingId + "','" + openingId + "')", 33);
}
I'd love to be able to put a #reel in the URL string and be able to navigate to, and open Accordion1Content.
You can use JQuery's pageready function, along with URL parsing to trigger a click event:
Say your URL looks like: http://mysite.com/?page=reel
$(function() {
var url = window.location.href;
var page = url.match(/page=([^\?]+)/)[1];
if (page=="reel") { runAccordion(1); }
});
You could add cases for the other page names as well.

Storing data in JavaScript array

This is my jsp code where I am trying to push some data in javaScript array.
<%
int proListSize = proList.size();
ProfileDAO proDAO = null;
for(int i = 0, j=1; i < proListSize; i++){
proDAO = (ProfileDAO)proList.get(i);%>
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + <%= proDAO.getCode()%>);
<%} %>
And this is the function where I am trying to use it by using pop function.
function GenDemographicTag() {
var ptag = "<!-- Begin "+networkNameToUpperCase+" -->\n" ;
var t = "";
if (WhiteTagLabelDomain) {
ptag += "<iframe src=\"http://"+WhiteTagLabelDomainTrim+"/jsc/"+folderName+"/dm.html?";
} else {
ptag += "<iframe src=\"http://"+cdnName+"/jsc/"+folderName+"/dm.html?";
}
ptag += "n="+networkId+";";
for(var i = 0;i< entireArray.length;i++){
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString.split(':')[0];
var middle = combinedString.split(':')[1];
var leftSide = combinedString.split(':')[2];
t = "";
if ( $("proElementEnable_"+rightSide) && $("proElementEnable_"+leftSide).checked) {
if ( middle == "1") {
if ( $("zip").value.length <= 0) {
t = "0";
} else {
t = $("zip").value;
}
} else if ( $("targetList_"+rightSide) && $("targetList_"+rightSide).length > 0 && $("targetList_"+rightSide).options[0].value != "-1") {
t = makeProelementList($("targetList_"+rightSide));
}
ptag += leftSide+"=" + t+ ";";
}
proDAO = null;
}
ptag += "\" frameborder=0 marginheight=0 marginwidth=0 scrolling=\"no\" allowTransparency=\"true\" width=1 height=1>\n</iframe>\n<!-- end "+networkNameToUpperCase+" -->\n";
document.forms[0].tag.value = ptag;
}
Basically I am trying to get the data from proList and store it in javaScript array(entireArray)...so that I can use in the javascript function..but after doing the above I get a javaScript error as follow:
entireArray.push(3 + ":"+3 + ":" + d3);
entireArray.push(185 + ":"+5 + ":" + d4);
entireArray.push(2 + ":"+2 + ":" + d2);
entireArray.push(186 + ":"+5 + ":" + d9);
entireArray.push(183 + ":"+5 + ":" + d6);
entireArray.push(184 + ":"+5 + ":" + d7);
entireArray.push(187 + ":"+5 + ":" + da);
entireArray.push(445 + ":"+5 + ":" + db);
Reference Error:d3 is not defined.
what is the exact problem..?
The return type of splice is an ARRAY , so you can try following code
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString[0].split(':')[0];
var middle = combinedString[0].split(':')[1];
var leftSide = combinedString[0].split(':')[2];
d3 should be in quotes. "d3"
You need to put the out of JSP in quotes.
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + '<%= proDAO.getCode()%>');

Categories

Resources