Seemingly simple but I can't find the correct placement. I have the following function in my HTML head:
<script>
(function($) {
$.fn.writeText = function(content) {
var contentArray = content,
current = 0,
elem = this;
setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 1000);
};
})(jQuery);
</script>
I call it in the body like:
<script>
// test getArray() method in external JS file
document.write(getArray());
$(document).ready(function($){
var contentArray = getArray();
$('#calculations').writeText(contentArray);
});
</script>
<h3>Fibonacci Sequence:</h3>
<p id='calculations'></p>
I can't find out where to place the '+ br /' to concatenate each writeText with a line break.
Using line breaks is a little amateur. Here's a script that appends paragraph tags.
$(function() {
var contentArray = ['first', 'second', 'third'],
iContent = 0;
function showContent() {
$('#calculations').append('<p>' + contentArray[iContent] + '</p>');
if (iContent < contentArray.length - 1) {
window.setTimeout(function () {showContent(); }, 1000);
iContent = iContent + 1;
}
}
window.setTimeout(function () {showContent(); }, 1000);
});
Also you don't need
$(document).ready(
A simple $( will do the same. Why are you doing a document.write() in your code? If you just want to see the array values a console.log() would work better.
I am taking a wild stab at what I think you are trying to do, but if I am correct, wouldn't this work?
$('#calculations').html(getArray().join('<br>'));
I would also not put JS in the head of your doc. Put it at the end the the body tag instead.
Related
I have a slice function set up, calling the index of a .test to fade in the .test divs in blocks of 5. There's a demo here: http://jsfiddle.net/neal_fletcher/JT4KB/2/
jQuery:
$(document).ready(function () {
$('.test').each(function (index) {
$('.test').slice(0, 5).delay(500).fadeIn(300);
$('.test').slice(5, 10).delay(1000).fadeIn(300);
$('.test').slice(10, 15).delay(1500).fadeIn(300);
});
});
This works fine, but as the site will be content managed I want a more compact solution, thus instead of having to write a function for every 5 divs, is there a way to call this function by adding an extra 500 onto the delay for every 5 divs? If that makes sense? Any suggestions would be greatly appreciated!
Here you go sir.
http://jsfiddle.net/JT4KB/17/
$(document).ready(function () {
setTimeout(function () {
$('.test').each(function (i) {
var delay = Math.floor(i/5)*500 + 500;
$(this).delay(delay).fadeIn(300);
});
}, 1000);
});
You can use a loop to achieve this. This loop has to loop 'the number of .test divs'/5 times:
$(document).ready(function () {
setTimeout(function () {
for (i=0; i<=$('.test').length/5; i++) {
$('.test').slice(5 * i, 5*(i+1)).delay(500*(i+1)).fadeIn(300);
};
}, 1000);
});
You can add a new method to jQuery like this:
$.fn.eachSlice = function(size, callback) {
var $t = $(this);
for(var i = 0; i < $t.length; i += size) {
callback.call($t.slice(i, i + size).get(), i / size);
}
return $t;
}
and then
$(".test").eachSlice(5, function(sliceIndex) {
$(this).delay(sliceIndex * 500).fadeIn();
});
http://jsfiddle.net/JT4KB/16/
Ok, I have been trying to make it work past 30 minutes.
Everything works fine in this jsfiddle :- http://jsfiddle.net/6KT4R/1/
But when I run this on my local wamp server..nothing seems to happen!.
Code :-
<script src="js/jquery-1.8.2.min.js" type="text/javascript">
</script>
<script type="text/javascript">
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
</script>
<input type="text" name="ltc" id="input-ltc">
<input type="text" name="btc" id="input-btc" readonly>
What is possibly wrong here?
Thanks.
The script is executing before the DOM is loaded. Try:
window.onload = function(){
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
}
As m59 suggested there is an improved method of executing the event onload. The following code snippet is preferred:
var funct = function(){
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
}
if (window.attachEvent){
window.attachEvent('onload', funct);
}else{
element.addEventListener('load', funct, false);
}
You're getting your element references before the elements exist on the page. In the jsfiddle, the javascript is executed after the html. You could reproduce this by moving your script tag below the related html. It is best practice to put all script tags just before the end of the body like this:
<script></script>
</body>
Otherwise, you'll need to register an event listener to watch for page load and execute your javascript code then.
window.addEventListener('load', function() {
console.log('loaded!');
});
with jQuery:
$(document).ready(function() {
console.log('loaded!');
});
//this is the jQuery shorthand for the same function above
$(function() {
console.log( "loaded!" );
});
I have the following information in a div
<div class="list">Abc, Test, Ready</div>
Below the div, I have this additional information
Remove Abc
Remove Test
Remove Ready
I am trying to write a jQuery function that will remove either Abc, Test, Ready (and the comma if necessary) when you click on the relevant remove link.
$('a').click(function() {
var str = $(this).attr("class");
$('.list').text($('.list').text().replace(str,''));
});
http://jsfiddle.net/PUure/
But if you really need commas removed, you need to be a bit more creative:
$('a').click(function() {
var str = $(this).attr("class");
var rgx = new RegExp(str + ',?\\s*');
$('.list').text($('.list').text().replace(rgx,''));
});
http://jsfiddle.net/PUure/4/
Edit: Updated for (lazily) removing trailing commas without regex ;)
Check the fiddle
$(document).ready(function(){
$('a').click(function(){
$('div.list').html($('div.list').html().replace($(this).attr('class') + ', ', '').replace($(this).attr('class'), ''));
});
});
You could do:
$('a').click(function(e){
e.preventDefault();
var word = $(this).attr('class');
var div = $('.list').text();
div = div.replace(word, '');
$('.list').text(div );
});
fiddle here http://jsfiddle.net/sysCc/
$('a').click(function(){
var str = $(this).attr('class');
var obj = $('.list');
var currentText = obj.text();
obj.text(currentText.replace(str,'');
});
or condensed:
$('a').click(function(){
$('.list').text($('.list').text().replace($(this).attr('class'),''));
});
You'd be better off keeping the data in an array, then modifying that array and refreshing your div with the new data.
var data = ["Abc", "Test", "Ready"];
refresh();
$("#Abc").click(function() { remove("Abc") });
$("#Test").click(function() { remove("Test") });
$("#Ready").click(function() { remove("Ready") });
function refresh() {
$("div").text(data.join(", "));
}
function remove(word) {
for(var i = 0; i < data.length; i++) {
console.log(i, data[i], word, data[i] == word);
if (data[i] == word)
data.splice(i, 1);
}
console.log(data);
refresh();
}
http://jsfiddle.net/Xeon06/dHp3b/
I have a page of more than 2500 anchor tag to process. Now in IE it is throwing the stop script error. Is it possible to do as a batch? Taking 500 executing it and then take the another 500 executing it??
This is the code...
ajaxLinks : function(el, flag) {
var links = $(el).find('a');
var notLinkAr=["a[href^=javascript]","#toolbarId ul li>a","#tool_settings .link a",".page-action-links li>a","#tool_settings .label a",".success-map .success-tabs li>a",".success-map .sm_loggedin li>a", ".analyst_cat li>a",".modal",".layer",".newpage",".close",".hideFromPopup",".pagenum",".next",".prev",".delete_src",".tips","#hidr","#backr"];
$(notLinkAr).each(function(index){
var notLinkI=$(notLinkAr[index]);
if($(notLinkI).is("a")){
if($(notLinkI).length>0){
$(notLinkI).each(function(index1){
$(notLinkI[index1]).addClass("dontAjaxify");
});
}
}
});
$(links).each(function(i, obj){
var link = $(obj);
if(!$(obj).hasClass('dontAjaxify')){
link.attr('rel', link.attr('href'));
var rellnk = link.attr('rel');
if(flag=='ajaxified') {
if(/http/.test(rellnk)){
var relurl;
relurl=rellnk.replace((window.location.protocol + "//"+ window.location.hostname),'')
link.attr('rel', relurl);;
}
}
link.bind('click', function(e){}
Iam adding a class for all the anchor tag(which is 2500) in a page.
jQuery's .slice may help you.
http://api.jquery.com/slice/
var count = 0;
var ajaxify = function (el, flags) {
var links = $(el).find('a').slice(count, count + 500);
count = count + 500;
// Do the processing here
if (links.length) {
// Call it next time only if some data is returned in the current call
setTimeout("ajaxify()", 5000);
}
}
The above code is not tested, but should probably work.
I have built a dropdown menu system, everything works when tested independently, the problem I have is in the code below. I use the jQuery ready function to build the menu bar from an external array (menubar[]). Here I am trying to get the mouseover event to call the dropdown() function, but using a different argument for each anchor tag.
So rolling over the first should call dropdown(0), the second dropdown(1) and so on.
$(document).ready(function () {
for (i in menubar) {
var declaration = '<a href="' + baseurl + '/' + menubar[i].url +
'" class="menutitle">' + menubar[i].name + '</a>';
var a = $(declaration).mouseover(function () {
dropdown(i);
}).mouseout(function () {
activeTimer = setTimeout("removedropdowns()", 100);
});
$("#menu").append(a);
}
});
The code is calling dropdown(6); on each rollover. How can I pass the loop variable (i) into the mouseover function as a literal/static value!
I got this working fine in FF by using
.attr('onMouseOver','javascript:dropdown('+i+');')
but that wasn't firing for some versions of IE, so I switched to the jQuery mouseover, which fires, but I have the issue above :(
Your actual problem is that each of your mouseover callbacks uses the same i you increase i all the way up to 6, the callbacks still point to the same i and therefore all use 6 as the value.
You need to make a copy of the value of i, you can do this by using an anonymous function.
$(document).ready(function () {
// you should use (for(var i = 0, l = menubar.length; i < l; i++) here in case menubar is an array
for (var i in menubar) {
var declaration = '<a href="' + baseurl + '/' + menubar[i].url +
'" class="menutitle">' + menubar[i].name + '</a>';
(function(e) { // e is a new local variable for each callback
var a = $(declaration).mouseover(function () {
dropdown(e);
}).mouseout(function () {
activeTimer = setTimeout(removedropdowns, 100); // don't use strings for setTimeout, since that calls eval
});
$("#menu").append(a);
})(i); // pass in the value of i
}
});
$(function() {
$(menubar).each(function(i){
$("#menu").append('' + menubar[i].name + '');
});
$("#menu a").hover(
function(){
dropdown($(this).index());
},
function(){
activeTimer = setTimeout("removedropdowns()", 100);
}
);
});
First, don't use for..in but rather ordinary loop.
Second, I would just append the links first then apply the events later:
$(document).ready(function() {
for (var i = 0; i < menubar.length; i++) {
$("#menu").append('' + menubar[i].name + '');
}
$("#menu a").each(function(index) {
$(this).mouseover(function() { dropdown(index); }).mouseout(function() { activeTimer = setTimeout("removedropdowns()", 100); });
});
});
Have a look here and here.
To capture the current value of i, you need to pass it as a parameter to another function where it can be captured as a local variable:
Try using jQuery's each() function:
jQuery(function() {
jQuery.each(menubar, function(index, element) {
var declaration = '' + element.name + '';
var a = $(declaration).mouseover(function() { dropdown(index); }).mouseout(function() { activeTimer = setTimeout("removedropdowns()", 100); });
$("#menu").append(a);
});
});
In JavaScript, if you don't declare your variable, it is defined globally. To fix this, add "var" in front of your i looping variable like this. UPDATE: As Sime noticed (see comment), you also need to pass the variable into the function, otherwise you form a closure on the i.
$(document).ready(function() {
for(var i in menubar) {
var declaration = '' + menubar[i].name + '';
var a = $(declaration).mouseover(function(i) { dropdown(i); }).mouseout(function() { activeTimer = setTimeout("removedropdowns()", 100); });
$("#menu").append(a);
}
});