Rewrite script from js to jquery - javascript

I have a script that I want to make more bulletproof. At the moment the page breaks because class box-tip is not found. To make this bulletproof and not throw an error how can I rewrote the below code to jquery getting the same results as js
function applyRecommendedSleeveLength(selectedVal) {
if (selectedVal !== undefined) {
var recommendedVal = map[selectedVal.trim()];
var selected = $('.attribute__swatch--selected:first div').text().trim();
if (recommendedVal === null || recommendedVal === undefined) {
selectedVal = $('.attribute__swatch--selected:first div').text().trim();
recommendedVal = map[selectedVal.trim()];
}
if (selected === null || selected === '' || selected === undefined) return;
var recommendedLis = document.querySelectorAll('[class*="attribute__swatch--length-' + recommendedVal + '"] div');
recommendedLis.forEach(function(recommendedLi, i) {
if (recommendedLi !== null && recommendedLi !== undefined) {
recommendedLi.classList.add('showBorder');
$('.box-tip').show();
var currentPosition = $('.showBorder').parent().position().left;
var sleeveRecom = document.getElementsByClassName('box-tip');
var info = sleeveRecom.length ? sleeveRecom[0] : false;
info.style.paddingLeft = currentPosition + -75 + 'px';
}
});
}
}

If you want to check if the div exists, you can use this (using JQuery):
if ( $('.box-tip').length != 0 ){
//do something
}
OR- since you've edited your post- without JQuery:
if ( document.getElementsByClassName('box-tip').length != 0 ){
//do something
}

Just use jQuery for all of this. If the class doesn't exist the jQuery methods won't cause errors
function applyRecommendedSleeveLength() {
$('.box-tip').show().first().css('paddingLeft', (currentPosition - 75) + 'px');
}

Related

jQuery - ui-selectmenu-button blur()-event

Okay - so for some reason or another, the jQuery UI Selectmenu-button messes with both focus() and blur()-events - they do not trigger. Is there a way to get these events to trigger, without having to use a function in the selectmenu()-assignment?
Reason I ask is that I have a overall function which is used for focus and blur-events on input, textarea and the like, which would be nice to also be able to use on selectmenu - but since it doesn't accept blur and focus, that makes it a bit more difficult.
Currently, I have the following code:
$('input,textarea,select').on('blur focus',function(event) {
var $this = $(this),
thisID = $this.attr('id'),
thisType = $this.attr('type'),
thisContent = $this.val(),
thisForm = $this.parents('form').attr('id'),
isRequired = $this.attr('required'),
getMessage = '',
elementPosition = $this.position(),
elementWidth = $this.width(),
elementHeight = $this.height(),
checkmarkPosition = (elementPosition != undefined) ? elementPosition.left + (elementWidth-10) : '',
topPosition = (elementPosition != undefined) ? Math.floor(elementPosition.top) : '';
if ($(this).hasClass('required')) {
thisContent = $this.text();
}
if (event.type == 'blur') {
if (isRequired == 'required' && (thisContent == '' || thisContent == 'Can\'t be empty')) {
getMessage = 'requiredField';
} else if (thisType == 'email') {
if (validateEmail(thisContent) == false) {
getMessage = 'notValidEmail';
} else {
getMessage = 'checkMark';
}
} else {
getMessage = 'checkMark';
}
}
if (getMessage != '' && getMessage != undefined) {
$.post('/returnmessages.php', {getmessage:getMessage}, function(data) {
data = $.parseJSON(data),
message = data.returnmessage,
infoState = data.infostate;
if (infoState != '' && infoState != undefined && thisType != 'submit') {
if (infoState == 'success') {
$this.addClass(infoState).after('<span style="position: absolute; left: '+(checkmarkPosition)+'px; top: '+(topPosition+10)+'px;" class="fa fa-check"></span>');
} else if (infoState == 'error' && (thisContent == '' || thisContent == undefined)) {
$this.addClass(infoState).prop('placeholder',message).next('span').remove();
}
}
})
}
})
Which works fine for regular events on regular inputs, but not on selectmenu-elements. It is a function to return "ok" (checkmarks) and different error-messages and such in the elements themselves, so no need to attach error-messages in separate elements.
Anyone have an idea as to how to make this work?
If you mean that select won't trigger your own function,you can use
$( "#selectionSomething" ).selectmenu({
change: function(){
$(this).trigger('blur')
}
});
hope it's useful

error Unable to get property 'display' of undefined or null reference

<script language="javascript">
function dropOrderDropDown() {
var currentInThisElement = document.activeElement.id
var currentInThisElementArray = currentInThisElement.split('_')
var foundOneToDrop = false;
var haveOneCurrentSelected = false;
var dropDownTempArray = new Array();
if ((dropDownDivValuesString != "") || (dropDownDivValuesString != null)){
dropDownTempArray = dropDownDivValuesString.split(',');
for (i=0; i < dropDownTempArray.length - 1; i++){
if (acdf != dropDownTempArray[i]){
if (document.all[dropDownTempArray[i] + "_hideThisControl"] != null){
if (document.all[dropDownTempArray[i] + "_hideThisControl"].style.display != "none"){
if (document.all[dropDownTempArray[i] + "_dropdown"] != null){
if (document.all[dropDownTempArray[i] + "_dropdown"].style.display == "block"){
document.all[dropDownTempArray[i] + '_txtValue'].click();
}
}
}
}
}
}
}
acdf = "";
return true;
</script>
First, I would recommend using getElementById() over document.all. document.all has limited browser support. Then, bear in mind that style only gets inline style properties. So if you aren't declaring style inline, you won't get any results.
Let me know if your issues persist!

addClass javascript for body-click background

i need to add one class at body when i click on.
i know is : $("body").addClass.("ex4Trigger"); but it doesn't work.
I want that when I click on the body, it does something like that =>
....
i dont know if he as possible with that :
var sasClickUrl = "/link/open";
var sasClickTarget = "_self";
document.write('<style>');
document.write('body {');
document.write('background-image: url("/gallery/background/image.jpg")!important;');
document.write('background-repeat: repeat-y;');
if ('top' == 'top with offset') {
document.write('background-position:center 0px;');
} else {
document.write('background-position:center top;');
}
if ('FFFFFF' != "") document.write('background-color: #FFFFFF;');
document.write('padding: 0px 0 0 0;');
if (0) document.write('background-attachment: inherit;');
if (sasClickUrl != "") document.write('cursor: pointer;');
document.write('}');
if (sasClickUrl != "" && !0) document.write('body > *{cursor: default;}');
document.write('</style>');
if (sasClickUrl != "") {
function OpenWin(page) {
if (sasClickTarget == "_parent") window.open(page);
else document.location = page;
}
sasBackClick2213491 = function (e) {
var bglink = sasClickUrl;
EE = e ? e : event;
if (!EE) return;
var tg = EE.target ? EE.target : EE.srcElement;
if ((!tg || tg.tagName != "BODY") && tg.parentNode.tagName != "BODY") return;
var BackLink = OpenWin("" + bglink);
};
document.onclick = sasBackClick2213491;
}
document.write('\r\n');
document.write('\r\n');
thx for help
(PS Sorry for my bad english)
$('body').click('function'){ $(this).addClass('ex4trigger'); }

Trigger alert function event for text area node in Firefox Javascript XUL

I want to trigger an alert if the user reached max number of characters in the text area.
Generally my plugin fill the user node values directly to my plugin text box. So, I want to generate an alert if the user reached var mymaxlength = 20;
var mymaxlength = 20;
if ( nodeName == "textarea" && node.value.length >= mymaxlength ) {
// call your popup / alert function
alert('hi, you have reached 20 characters');
}
I have tried the above code, it didn't work without any errors? In my full code, the general alert is working but the alert inside the loop is not working?
1. Is it a good way of triggering an alert in onKeypress : function (e)? or
2. Would it be possible to trigger an alert if the user node has filed 20 characters in the fillText : function (node)?
Please assist me!
This is the full code:
run : function () {
//alert(content.document.cookie);
//alert("-"+content.document.cookie+"-");
var cookieTest = content.document.cookie
var JSESSIONID = pdees.get_Cookie("JSESSIONID");
if(verifyConnection){
if(JSESSIONID && cookieTest){
//var result = verifyUserIdentity(JSESSIONID);
var head = content.document.getElementsByTagName("head")[0];
var body = content.document.body;
//var style = content.document.getElementById("pdees-style");
//var allLinks = content.document.getElementsByTagName("pdees");
var foundLinks = 0;
//extract text element from body
if(document.getElementById && document.createTreeWalker && typeof NodeFilter!="undefined"){
var tw=document.createTreeWalker(body,NodeFilter.SHOW_TEXT,null,false);
lookForpdees(tw);
}
addJScode();
idpdeesbutton=0;
}else{
alert("You should connect to the Application Environment to be authentified");
}
}else{
//var result = verifyUserIdentity(JSESSIONID);
var head = content.document.getElementsByTagName("head")[0];
var body = content.document.body;
//var style = content.document.getElementById("pdees-style");
//var allLinks = content.document.getElementsByTagName("pdees");
var foundLinks = 0;
//extract text element from body
if(document.getElementById && document.createTreeWalker && typeof NodeFilter!="undefined"){
var tw=document.createTreeWalker(body,NodeFilter.SHOW_TEXT,null,false);
lookForpdees(tw);
}
addJScode();
idpdeesbutton=0;
}
},
onKeypress : function (e) {
var mymaxlength = 20;
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//text area cache onKeyPress code
//alert('hi1');
if ( nodeName == "textarea" && node.value == "" && e.keyCode == 13 ) {
pdees.fillText(node);
return;
}
if ( nodeName == "textarea" && node.value.length >= mymaxlength ) {
// call your popup / alert function
alert('hi, you have reached 20 characters');
}
// this node is a WYSIWYG editor or an editable node?
if ( ( nodeName != "html" || node.ownerDocument.designMode != "on" ) && node.contentEditable != "true" )
return;
if ( node.textContent == "" && e.keyCode == 13 ) {
pdees.fillText(node);
return;
}
if (!node.tacacheOnSave) {
pdees.fillText(node);
}
},
onChange : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//alert("onChange : "+nodeName);
if ( nodeName != "textarea" )
return;
pdees.fillText(node);
},
onInput : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//alert("onInput : "+nodeName);
// Only for textarea node
if ( node.nodeName.toLowerCase() != "textarea" )
return;
if ( node.value == "" )
return;
pdees.fillText(node);
},
fillText : function (node) {
nodeSRC = node;
if ( node.nodeName.toLowerCase() == "textarea" )
{
//alert('hi');
userContent = node.value;
//alert(userContent);
}
else if ( node.nodeName.toLowerCase() == "html" ) {
userContent = node.ownerDocument.body.innerHTML;
//alert(userContent);}
}
else // element.contentEditable == true
userContent = node.innerHTML;
},
emptyNodeSRC : function (node){
if ( node.nodeName.toLowerCase() == "textarea" ) {
node.value = "";
}
else if ( node.nodeName.toLowerCase() == "html" ) {
node.ownerDocument.body.innerHTML = "";
}
else // element.contentEditable == true
node.innerHTML = "";
},
};
}();
Finally, I have found my problem and I have succeed to trigger mu custom alert:
In this function fillText : function (node)where I can trigger an alert for the userContent. So I made a length and triggered an alert for it.
else if ( node.nodeName.toLowerCase() == "html" ) {
userContent = node.ownerDocument.body.innerHTML;
//alert(userContent);
var myTest = userContent.length;
if(userContent.length == 30)
{
alert('Hi, there!');
}
}
else // element.contentEditable == true
userContent = node.innerHTML;
},
Note: For complete code please refer to my question.

modify click event script to be more specific

I have to the following function that I would like to modify so that it only binds the click event to all href's that = /ShoppingCart.asp?ProductCode="whatever" (whatever = whatever is in there") but not if it is specifically /ShoppingCart.asp?ProductCode="GFT". It must also check or convert a gft or Gft to upper case to check for those as well. So basically it has to check for any variation of the case of GFT.
If it finds a "GFT" do not bind the click event.
function sacsoftaddtocart() {
if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
$("a[href^='/ShoppingCart.asp?ProductCode']").click(function () {
var href = $(this).attr('href');
addToCart3(href);
return false;
});
}
}
You can do it using .toUpperCase() and .filter(), like this:
function sacsoftaddtocart (){
if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
$("a[href^='/ShoppingCart.asp?ProductCode']").filter(function() {
return this.href.length - this.href.toUpperCase().indexOf('PRODUCTCODE=GFT') != 15;
}).click(function () {
var href = $(this).attr('href');
addToCart3(href);
return false;
});
}
}
You cant test it in a demo here. The this.href.length - matchPosition == 15 is checking that the ProductCode=GFT is both matched and there's nothing after the "GFT", so a product code like "GFT5" won't match.
using the filter in this post link text
function sacsoftaddtocart() {
if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
$("a:regex('href','*/ShoppingCart.asp\?ProductCode=(!?=GFT)*)").click(function () {
var href = $(this).attr('href');
addToCart3(href);
return false;
});
}
}
or if you don't want to use an exrat plugin:
function sacsoftaddtocart() {
if (location.pathname == "/SearchResults.asp" || location.pathname == "/Articles.asp" || location.pathname.indexOf("-s/") != -1 || location.pathname.indexOf("_s/") != -1) {
$("a['href^='/ShoppingCart.asp?ProductCode']")
.filter(function(){ return !/ProductCode=GTF/.test($(this).attr('href')) };
.click(function () {
var href = $(this).attr('href');
addToCart3(href);
return false;
});
}
}
Try them and see what happens ;)

Categories