Javascript doesn't work when have another one - javascript

I searched but I didn't find the answer.
I have a code that change the color of my wordpress template blocks and posts randomly. Actually it changes the classes of these blocks and so the colors. You can see the code here:
function inArray(array , exist) {
var rslt = false;
for (var j = 0; j < array.length; j++)
{
if (array[j] == exist)
{
rslt = true;
}
}
return rslt;
}
var colored = Array();
function changeColor(target) {
var blocks = document.getElementsByClassName(target);
var blockLength = blocks.length;
for (var i = 0; i < blockLength; i++)
{
if (colored.length >= 9)
{
colored = [];
}
var rand = 0;
while (rand == 0 || inArray(colored , rand))
{
rand = Math.floor(Math.random()*10)%10;
}
colored.push(rand);
blocks[i].className = target+' color'+rand ;
}
}
window.onload = function() {
changeColor('block');
changeColor('post');
}
the code you seen placed in an external file named 'colors.js' and included by:
<script src="<?php bloginfo('template_url'); ?>/scripts/colors.js"></script>
in my wordpress template.
the code works correctly til I add another code like this:
<script>var _mxvtmw_position = 'left', _mxvtmw_domain = 'icomp.ir'</script>
<script src="http://iwfcdn.iranwebfestival.com/js/mx.vtmw.min.js?12688" async="async"></script>
Why? And how can i fix this problem?
Thank you.
EDIT:
DEMO: http://tuts.icomp.ir/

IN CASE blocks.length IS 1 YOU HAVE TO ADD ONE MORE IF CONDITION
if (blocks.length==undefined){
//code
}

Related

How to create a function to be re-used for later within another function

I got this code:
$(document).ready(function(){
$(".nextForm").on('click',(function(){
//check criteria
if(selectedSlots.length < 1 ||$("#positionAppliedFor").get(0).value.length < 1 ||$("#maxAmountOfHours").get(0).value.length < 1){
//error messages and array
var errorForSlots= "<h5>Select at least one availability slot</h5>";
var errorForPosition = "<h5>Enter the position you wish to apply for<h5>";
var errorForHours = "<h5>Enter the amount of hours you would like to work<h5>";
var errors = [];
//add errors to array
if(selectedSlots.length < 1){errors.push(errorForSlots)};
if($("#positionAppliedFor").get(0).value.length < 1){errors.push(errorForPosition)};
if($("#maxAmountOfHours").get(0).value.length < 1){errors.push(errorForHours)};
//create message
var div = "<div id=\"sectionError\">";
if($("#sectionError").length > 0){$("#sectionError").html('')};
$(div).appendTo($(this).get(0).parentNode);
for(var i = 0; i < errors.length; i++){
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);}
$("</div>").appendTo($(this).get(0).parentNode);
} else {
$("#applicationDetails").slideUp();
$("#personalDetails").slideDown();
if($("#sectionError").length > 0){$("#sectionError").remove()};
}
console.log("function finished");
}));
It all works perfectly, however, I am trying to figure out how to create a function for
//create message
var div = "<div id=\"sectionError\">";
if($("#sectionError").length > 0){$("#sectionError").html('')};
$(div).appendTo($(this).get(0).parentNode);
for(var i = 0; i < errors.length; i++){
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);}
$("</div>").appendTo($(this).get(0).parentNode);
I am planning to re-use this for few other sections on my form and rather than copy/paste I would like to get some help on making my code tidier.
I did try:
function myFunction(){
//message code here
}
$(document).ready(function(){
$(".nextForm").on('click',(function(){
//check criteria
...
//add errors
...
//call func
myFunction();
(I also tried this.myFunction();)
...
}));
});
However, that ended up in TypeError and I don't know where to begin...
I am also concerned about the "this" in my message code so I am also not sure how to address that in my new function...
Admitedly I am a newbie at this and I do not exactly understand all the ins and outs, hopefully you will be able to help.
Maybe there is a better way of doing this?
Let me know your thought either way!
Thanks.
I have created a small reusable framework same as how jQuery is doing behind the scene to expose reusable functions. I didn't tested the append function properly,I just explaining how you can create your own reusable plugin to reuse across the project.
You can change the parameters and method name that you want to expose based on your functionality.
Also I would suggest you to move this code to a javascript file as a plugin and drag after the jquery script.
(function (global, $) {
//you can pass the jQuery object in to this IIFE
var DisplayError = function (elementId) {
return new DisplayError.init(elementId);
}
DisplayError.prototype = {
appendError: function (errors) {
var div = "<div id=\"" + this.elementId + " \">";
if ($(this.elementId).length > 0) {
$(this.elementId).html('')
};
$(div).appendTo($(this.elementId).get(0).parentNode);
for (var i = 0; i < errors.length; i++) {
$(errors[i]).appendTo($(this.elementId));
}
$("</div>").appendTo($(this.elementId).get(0).parentNode);
}
};
DisplayError.init = function (elementId) {
var self = this;
self.elementId = elementId;
}
DisplayError.init.prototype = DisplayError.prototype;
global.DisplayError = global.DisplayError = DisplayError;
}(window, jQuery));
You can write the code for clear the html directly in init function to ensure the element is clearing while initialize the instance itself.
You can invoke the method like below ,
var displayError=DisplayError("#sectionError")
displayError.appendError(["errorId"])
or
DisplayError("#sectionError").appendError(["errorId"])
Hope this helps
New Function
function generateMessage(arg1) {
//create message for each section
console.log("generating message");
var div = "<div id=\"sectionError\">";
if ($("#sectionError").length > 0) {
$("#sectionError").html('')
}
;$(div).appendTo($(arg1).parent());
for (var i = 0; i < errors.length; i++) {
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);
}
$("</div>").appendTo($(arg1).parent());
}
Changed old function
$(document).ready(function() {
$("#adbutnext").on('click', (function() {
//check criteria
if (selectedSlots.length < 1 || $("#positionAppliedFor").get(0).value.length < 1 || $("#maxAmountOfHours").get(0).value.length < 1) {
//error messages and array
var errorForSlots = "<h5>Select at least one availability slot</h5>";
var errorForPosition = "<h5>Enter the position you wish to apply for<h5>";
var errorForHours = "<h5>Enter the amount of hours you would like to work<h5>";
errors = [];
//add errors to array
if (selectedSlots.length < 1) {
errors.push(errorForSlots)
}
;if ($("#positionAppliedFor").get(0).value.length < 1) {
errors.push(errorForPosition)
}
;if ($("#maxAmountOfHours").get(0).value.length < 1) {
errors.push(errorForHours)
}
;
generateMessage(this);
} else {
$("#applicationDetails").slideUp();
$("#personalDetails").slideDown();
if ($("#sectionError").length > 0) {
$("#sectionError").remove()
}
;
}
console.log("function finished");
}
));
});

Javascript not working on GoDaddy hosting

Here is my code.
var cSharpButtons = document.getElementsByClassName("csharpbutton");
var jSButtons = document.getElementsByClassName("jsbutton");
var cSharp = document.getElementsByClassName("csharp");
var jS = document.getElementsByClassName("js");
function switchToCSharp()
{
for (i = 0; i < cSharpButtons.length; i++) //change button colors
{
cSharpButtons[i].style.backgroundColor = "#00AEEF";
}
for (i = 0; i < jSButtons.length; i++)
{
jSButtons[i].style.backgroundColor = "lightgrey";
}
for (i = 0; i < cSharp.length; i++) //change code
{
cSharp[i].style.display = "inline";
}
for (i = 0; i < jS.length; i++)
{
jS[i].style.display = "none";
}
}
function switchToJS()
{
for (i = 0; i < jSButtons.length; i++) //change button colors
{
jSButtons[i].style.backgroundColor = "#00AEEF";
}
for (i = 0; i < cSharpButtons.length; i++)
{
cSharpButtons[i].style.backgroundColor = "lightgrey";
}
for (i = 0; i < cSharp.length; i++) //change code
{
cSharp[i].style.display = "none";
}
for (i = 0; i < jS.length; i++)
{
jS[i].style.display = "inline";
}
}
GoDaddy said the permission were fine. Works like a charm on my desktop, they said something must be wrong with my code. They said it could be an outdated way of coding it.
nothing happens when you press a button, to try it for yourself visit http://spacehelmetstudios.com/tutorials/unity2d/directionalgravity2d/directionalgravity2d.html and try to change it from C# to JS.
I'm not going to lie, I don't know very much about the server side of things.
Any ideas? Thanks.
I know this isn't an answer, but in developers console I don't see any JS file downloaded and i get a console error saying that your functions are not defined. Maybe you forgot to add your JS files in your <head> tag?

for loop failing to loop continuously

var _target=document.querySelectorAll('.post .content');
var isYT = /youtube|youtu.be/gi;
for (i = 0; i < _target.length; i++) {
var _tar = _target[i].children;
for (var j = 0; j < _tar.length; j++) {
var vidID;
if (_tar[j].tagName == "A") {
if (isYt.test(_tar[j].href) == true) {
_eles.push(_tar[j]);
}
}
if (_tar[j].tagName == "EMBED") {
if (isYt.test(_tar[j].src) == true) {
_eles.push(_tar[j]);
}
}
} //end for loop j
} //end for loop i
console.log(_eles);
The HTML looks sort of like this:
<div>
Video 1
Video 2
<embed src="www.youtube.com/v/239324"></embed>
</div>
<div>
Video 1
Video 2
<embed src="www.youtube.com/v/239324"></embed>
</div>
Though the returning array Object with my console logging is only showing one a element and one embed element. I have to continuously invoke this myself to get all the links and embeds to be placed into the array Object. Any one see any errors I've written, just been working on this issue for about 3 hours now and it is tiring me. Any help is greatly appreciated.
thank you
I have changed your code this way:
var _target = document.querySelectorAll("div");
var _eles = [];
var isYt=new RegExp("\youtube.com");
for (var i = 0; i < _target.length; i++) {
var _tar = _target[i].childNodes;
for (var j = 0; j < _tar.length; j++) {
var vidID;
if(_tar[j].nodeType != 1) continue;
if (_tar[j].tagName.toLowerCase() == "a") {
if (isYt.test(_tar[j].href)) {
_eles.push(_tar[j]);
}
}
if (_tar[j].tagName.toLowerCase() == "embed") {
if (isYt.test(_tar[j].src)) {
_eles.push(_tar[j]);
}
}
} //end for loop j
} //end for loop i
console.log(_eles);
and it works, check this DEMO
but my favorite way to do this is like this:
var _target = document.querySelectorAll("div>a, div>embed");
var _eles = [];
var isYt=new RegExp("\youtube.com");
for (var j = 0; j < _target.length; j++) {
var vidID;
if (_target[j].tagName.toLowerCase() == "a") {
if (isYt.test(_target[j].href)) {
_eles.push(_target[j]);
}
}
if (_target[j].tagName.toLowerCase() == "embed") {
if (isYt.test(_target[j].src)) {
_eles.push(_target[j]);
}
}
} //end for loop j
console.log(_eles);
for this check this one DEMO
and if your isYT regexp is just as simple as I have used in my answer instead of all these lines of code you can simply do:
var _eles = document.querySelectorAll("div>a[href*='youtube.com/'],"+
"div>embed[src*='youtube.com/']");

Create dynamic elements in javascript and visualize it on UI as soon as the node is created

I am working on a script that creates a tree. The problem i am facing is when large chunk of data comes it gets stuck for some time then rendering every thing at the end.
What i am looking for is can there be a way that make it more interactive. Like as soon as a node is being made it gets popup at the Interface.
For getting into the inside i am posting my code.
function recursiveGenerateTree(objNode, parntSpan, ulContainer, objEditParam) {
var cntLi = 0;
var spnApplyClass;
var rdbValue;
var cntrList = 0;
for (cntLi = 0; cntLi <= objNode.NodeList.length - 1; cntLi++) {
objEditParam.rdbGroup = objEditParam.rdbGroup;
rdbValue = objEditParam.orgRootID + '_' + objNode.NodeList[cntLi].Id;
objEditParam.rdbValue = rdbValue;
objEditParam.selector = 'radio';
objEditParam.selector = '';
objEditParam.isNewNode = false;
addChild('', parntSpan, ulContainer, objEditParam);
$('#txtParent').val(objNode.NodeList[cntLi].Name);
spnApplyClass = $('#txtParent').parents('span:first');
$('#txtParent').trigger('blur', [spnApplyClass]);
spnApplyClass.removeClass('bgLime');
var li = spnApplyClass.parents("li:first");
li.attr("nodeId", objNode.NodeList[cntLi].Id);
li.attr("rootnodeId", objNode.NodeList[cntLi].RootOrgUnitId);
var ulPrsnt = objNode.NodeList[cntLi].NodeList;
if (ulPrsnt != undefined && ulPrsnt.length > 0) {
recursiveGenerateTree(objNode.NodeList[cntLi], spnApplyClass, '', objEditParam);
}
}
}
Second function used is Add child
function addChild(currentbtn, parentSpn, parentUl, objEditParam) {
var spnElement;
if ($(currentbtn).length > 0) {
var dvClick = $(currentbtn).closest('div').siblings('div.OrgGroupLists')
spnElement = $(dvClick).find('span.bgLime');
}
else {
spnElement = parentSpn;
}
if (spnElement.length == 0 && parentUl.length == 0)
return;
var crtUlChild;
if (spnElement.length > 0) {
var dvCurrent = $(spnElement).closest("div");
crtUlChild = $(dvCurrent).find('ul:first');
}
if (parentUl.length > 0) {
crtUlChild = parentUl;
}
if (crtUlChild.length == 0) {
var ulChildrens = createUl();
}
//Next line needs to be updated.
var spnImage = $(dvCurrent).find("span:first");
$(spnImage).removeClass("SpanSpace");
$(spnImage).addClass("L7CollapseTree");
var liChildrens = document.createElement("li");
$(liChildrens).attr("isNew", objEditParam.isNewNode);
$(liChildrens).attr("isTextEdited", false);
var dvChildrens = createDivNode(objEditParam);
$(liChildrens).append(dvChildrens);
if (crtUlChild.length == 0) {
$(ulChildrens).append(liChildrens);
$(dvCurrent).append(ulChildrens);
}
else {
crtUlChild.append(liChildrens);
}
}
Feel free to ask any more details if required to understand the problem more clearly.
What #nnnnnn means is that you call subsequent recursion in setTimeout.
I did not spend time trying to replicate your code locally. Check out JavaScript code below for example. setTimeout works fine for the code below. You can vary variable j's length according to your browser. The inner loop j is to block JS thread.
<html><head>
<script>
var k = 0;
function recursiveTree(){
$("#holder").append("<div>Item</div>");
for(var j =0; j < 100000000; j++){
// blocking thread
}
if (k++ < 20) {
console.log(k);
setTimeout(function(){recursiveTree()},10);
}
}</script>
</head>
<body>
<div id='holder'></div></body>
</html>
I assumed that you are using JQuery.
Just to confirm you need to make recursive call as following
if (ulPrsnt != undefined && ulPrsnt.length > 0) {
setTimeout(function(){recursiveGenerateTree(objNode.NodeList[cntLi], spnApplyClass, '', objEditParam);},10);
}

str.split() inside $(document).ready() does not work?

http://jsfiddle.net/MQHkA/2/
$(document).ready(function() {
var mystring="fusioncharts,om,bdutt";
var arr = mystring.split(','); //array returned
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
}
Would the above code work ?
EDIT---
Well the real code block is this :
handle1 = getUrlVars();
if(handle1 == '') {
$("input#handle1").val('barackobama');
$("input#handle2").val('aplusk');
$("input#handle3").val('charliesheen');
handle1 = 'barackobama,aplusk,charliesheen';
} else {
alert(handle1); // this says fusioncharts,om,bdutt
var queryvals = [];
queryvals = handle1.split(',');
alert('length'+queryvals.length); // *** this says nothing ***
for(var i = 0; i < queryvals.length; i++) {
alert(queryvals[i]); // *** nothing here too.. ****
}
}
And the entire block is in a $(document).ready()...
Must be some simple error which I'm unable to spot..
you are missing the closing parentheses other than that it works fine
$(document).ready(function() {
var mystring="fusioncharts,om,bdutt";
var arr = mystring.split(','); //array returned
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
}); // this one is missing on yours
Yes, but you have to close off your example with
);
http://jsfiddle.net/gMU9t/
You forgot to close your parentheses and already have sounded the alarm. Debug your code before asking. Javascript functions work fine. You need to be more attentive.

Categories

Resources