I'm looking to change this script so that the animation starts once the page has loaded instead of when the div is clicked on.
Any suggestions on how I could do this would be much appreciated.
Here is the JS
$(document).ready(function() {
$(".marqueeElement").last().addClass("last");
$(".mholder").each(function() {
var i = 0;
$(this).find(".marqueeElement").each(function() {
var $this = $(this);
$this.css("top", i);
i += $this.height();
});
});
$('.mholder').click(function() {
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
});
function doScroll($ele) {
var top = parseInt($ele.css("top"));
if (top < -60) { //bit arbitrary!
var $lastEle = $ele.closest('.mholder').find(".last");
$lastEle.removeClass("last");
$ele.addClass("last");
var top = (parseInt($lastEle.css("top")) + $lastEle.height());
$ele.css("top", top);
}
$ele.animate({
top: (parseInt(top) - 60)
}, 80, 'linear', function() {
doScroll($(this))
});
}
Just move the code inside the .ready() event.
$(document).ready(function() {
$(".marqueeElement").last().addClass("last");
$(".mholder").each(function() {
var i = 0;
$(this).find(".marqueeElement").each(function() {
var $this = $(this);
$this.css("top", i);
i += $this.height();
});
});
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
Assuming '.mholder' is the selector for your div, just get rid of the click handler - i.e. change from:
$('.mholder').click(function() {
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
to
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
the most easiest way is to put at the end of the on ready function the following (after you bind the click event):
$('.mholder').click()
Related
I have this HTML code:
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>
And i want to execute this JavaScript code on each one:
$(document).ready(function() {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#dadosalvaje');
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#dadosalvaje').attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
});
It just affects the first element and I can't find the way to modify both of them.
Is there any way to modify every single element with the same ID ?
First you need to make unique id
You do not need the "draconistone" class
Inside the $(document).ready(function() { and }); tags make the code a function with an id parameter like this:
function name(id) {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#' + id);
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#' + id).attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
}
Then execute the functions with the two different ids as parameters.
Maybe you can use $.each()
Like this
$('.draconistone').each(function() {
var zonaID = $(this).attr('class');
..
});
There is one for the same class
$( document).ready(function() {
$( ".draconistone" ).each(function( i ) {
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var texto = this.innerText.split(' ');
var resultado = texto.pop();
var zonaID = this.className;
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
this.innerHTML += '<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>';
this.id = 'salvajelisto';
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dadosalvaje1" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje2" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>
When a div is clicked, fires function, in which, on mousedown, new div is created, and in that new div the clicked one and some others are appended (all of those appended divs are have draggable plugin on them). My question is: how do I drag the new div? As you will notice, I tried using handle, but failed.
var game = this;
var cardOldLocationId;
var tempWraperSelector;
$('#playArea').children().on('mousedown', function(event) {
tempWraperSelector = $('<div id="multipleCardSelector"> </dv>');
$(tempWraperSelector).appendTo('#' + $(event.target).parent().parent().attr('id'));
cardOldLocationId = $(event.target).parent().parent().attr('id');
var selectedCardIndex;
var cardsToAppend = [];
var pressedRowLenght = game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]].length;
for (var i = 0; i < game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]].length; i++) {
if (game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]][i].Taskai + "_" + game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]][i].Simbolis === $(event.target).attr('id')) {
selectedCardIndex = i;
break;
}
}
for (var j = selectedCardIndex; j < pressedRowLenght; j++) {
var cardSelector = '#' + game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]][j].Taskai + "_" + game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]][j].Simbolis;
cardsToAppend.push(cardSelector);
}
for (var k = 0; k < cardsToAppend.length; k++) {
$(cardsToAppend[k]).parent().appendTo(tempWraperSelector);
}
$(tempWraperSelector).draggable({
handle: '#' + $(event.target).attr('id')
});
});
$('#playArea').children().on('mouseup', function(event) {
$(tempWraperSelector).children().appendTo('#' + cardOldLocationId);
$(tempWraperSelector).remove();
});
I am using Bootstrap.
I am not able to figure out how to put this in pure javascript.This will open a div when we click on the accordion.
$(function() {
$("#panelTicketsList .list-group-item").on("click", function() {
$("#panelTicketsList .list-group-item").removeClass('selected');
$(this).addClass('selected');
if ($('#panelTicketsList').hasClass('col-md-12')) {
$('#panelTicketsList').removeClass('col-md-12').addClass('col-md-3');
$('.panelTicketDetail').removeClass('hide');
}
});
});
jsFiddle : https://jsfiddle.net/tqdc6yyL/
var listGroupItems = document.getElementsByClassName('list-group-item');
for (j = 0; j < listGroupItems.length; j++) {
listGroupItems[j].addEventListener("click", function () {
var elements = listGroupItems;
for (i = 0; i < elements.length; i++) {
if (elements[i].className.indexOf("col-md-12") > -1) {
elements[i].className = elements[i].className.replace("col-md-12", "col-md-3");
elements[i].className = elements[i].className.replace("hide", "");
}
}
this.className = this.className + " selected";
});
}
var list = document.getElementById('panelTicketsList');
var items = document.querySelectorAll("#panelTicketsList .list-group-item");
var detail = document.querySelectorAll(".panelTicketDetail");
items.forEach(function(btn){
btn.addEventListener("click", function(){
items.forEach(function(item){ item.classList.remove("selected"); });
this.classList.add("selected");
if(list.classList.contains('col-md-12')) {
list.classList.remove('col-md-12');
list.classList.add('col-md-3');
detail.classList.add("hide");
}
});
If you have to support older browsers like IE8 or IE9, you can't use JS features like forEach or classList. Instead you should use for loop and className.
//Save DOM query in variable for reuse
var panelTicketsList = document.getElementById('panelTicketsList');
var panelTicketsDetails = document.getElementsByClassName('panelTicketDetail');
var listGroupItems = panelTicketsList.getElementsByClassName('list-group-item');
//go through all of the listGroupItems and set click listener
for (var i = 0; i < listGroupItems.length - 1; i++) {
listGroupItems[i].addEventListener("click", function() {
//On click, go through all of listGroupItems and remove selected class
for (var j = 0; j < listGroupItems.length - 1; j++) {
listGroupItems[j].className = listGroupItems[j].className.replace('selected', '');
}
//Add selected class for clicked element
listGroupItems[i].className += 'selected';
//test if main element has class col-md-12
if (panelTicketsList.className.indexOf("col-md-12") > -1) {
//replace clas col-md-12 with col-md-3
panelTicketsList.className = panelTicketsList.className.replace('col-md-12', 'col-md-3');
//go through all of the panelTicketDetails and remove hide class
for (var k = 0; k < panelTicketsDetails.length - 1; k++) {
panelTicketsDetails[k].className = panelTicketsDetails[k].className.replace('hide', '');
}
}
});
}
I am trying to render child elements of an element if the element is in view or removing the content if not in view like below on scroll event like below
list.addEventListener('scroll', function () {
var elements = document.querySelectorAll('.aBox');
var toBe = counter - 1 - elements.length;
for (var i = 0; i < elements.length; i++) {
var inView = visibleY(elements[i]),
ele = elements[i].querySelector('.item');
if (inView === false && ele) {
console.log("Not in visible, keeping it none");
var height = elements[i].clientHeight;
elements[i].style.height = height + "px";
elements[i].innerHTML = "";
} else if(!ele){
console.log('Placing the content');
var minArray = arr[toBe + 1 + i],
str = "";
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
elements[i].innerHTML = str;
}
}
});
It seems working but if I have a look at the DOM this is not working as expected. Someone please help me to find the problem, fiddle.
Update
function updateData(callback) {
var elements = document.querySelectorAll('.aBox');
elements = Array.prototype.slice.call(elements);
var toBe = counter - 1 - elements.length;
async.each(elements, function (element, cb) {
var inView = $(element).is_on_screen(),
ele = element.querySelector('.item');
if (inView == false && ele) {
console.log("Not in visible, keeping it none");
var height = element.clientHeight;
element.style.height = height + "px";
element.innerHTML = "";
} else if (!ele && inView) {
console.log('Placing the content');
var minArray = arr[toBe + 1 + i],
str = "";
if (typeof minArray === "object") {
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
element.innerHTML = str;
}
}
cb();
}, function () {
callback()
});
}
Fiddle
Hi I have solved this problem. Posting here, so that it will be more helpful for people who want to work on mobiles to display very large lists with virtual scrolling
var arr = new Array(10000);
for (var i = 0; i < arr.length; i++) {
arr[i] = "Hello Dudes..." + i;
}
Array.prototype.chunk = function (chunkSize) {
var array = this;
return [].concat.apply([],
array.map(function (elem, i) {
return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
}));
}
arr = arr.chunk(50);
var list = document.getElementById('longList');
var button = document.getElementById('loadMore');
var counter = arr.length,
aBoxLen = 1;
function appendBox() {
var div = document.createElement('div'),
str = "";
div.className = "aBox";
var minArray = arr[counter - aBoxLen];
for (var i = 0; i < minArray.length; i++) {
str += "<div class='item'>" + minArray[i] + "</div>";
}
div.innerHTML = str;
div.setAttribute('index', counter - aBoxLen);
var box = document.querySelector('.aBox');
if (box) {
list.insertBefore(div, box);
} else {
list.appendChild(div);
}
aBoxLen += 1;
}
appendBox();
button.addEventListener('click', function () {
appendBox();
});
$.fn.is_on_screen = function () {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
function updateData(callback) {
var elements = document.querySelectorAll('.aBox');
elements = Array.prototype.slice.call(elements);
var toBe = counter - 1 - elements.length;
async.each(elements, function (element, cb) {
var inView = $(element).is_on_screen(),
ele = element.querySelector('.item');
if (inView == false && ele) {
console.log("Not in visible, keeping it none");
var height = element.clientHeight;
element.style.height = height + "px";
element.innerHTML = "";
} else if (!ele && inView) {
console.log('Placing the content');
console.log(element.getAttribute('index'));
var minArray = arr[element.getAttribute('index')],
str = "";
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
element.innerHTML = str;
}
cb();
}, function () {
// callback()
});
}
var delay = false;
var timeout = null;
list.addEventListener('touchmove', function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
updateData();
}
}, delay);
});
None of the solutions were specifically designed for mobiles, so I have implemented this.
I think there is lots of space for improvement in this. If anybody want to improve it, please feel free to make it
Demo
I've wrote this so it changes the href of the anchor with the class name but I also would like it to change the target, how do I add this?
window.onload = function() {
var change = document.getElementsByTagName('a');
for (var i = 0; i < change.length; i++) {
if (change[i].className.match('(^|\\s+)classnamegoeshere(\\s+|$)')) {
change[i].href = "/urlgoeshere";
break;
}
}
}
change[i].setAttribute('target', '_blank');
Try this
window.onload = function() {
var change = document.getElementsByTagName('a');
for (var i = 0, j =change.length; i < j ; i++) {
if ((' ' + change[i].className + ' ').indexOf(' ' + "smeCls" + ' ') > -1) {
change[i].href = "http://www.google.com";
}
}
}