Unable to get forEach to properly work on IE - javascript

I completed a active/disable feature in my code that works on both Chrome/Firefox really well but for some reason I am getting an error in IE when using forEach.
Here is the error that is being displayed on IE:
On Chrome & Firefox, the div's highlight the box and the correct box shows up below.
Here is the code that I am using:
"use strict";
var tabButtons = document.querySelectorAll('.navlinksGP > a');
function enableTabButton(buttonId) {
tabButtons.forEach(function(btn) {
if (btn.id === buttonId) {
btn.disabled = true;
btn.style.background = '#eeaf00';
btn.style.color = '#ffffff';
} else {
btn.disabled = false;
btn.style.background = '#ffffff';
btn.style.color = '#eeaf00';
}
});
}
enableTabButton('word');
var player = document.getElementById('player');
function wButton(element) {
enableTabButton(element);
if (element === "word") {
player.innerHTML = "<h1 id=\"h1update\">Brand & Consumer Marketing</h1>";
}
<div class="navlinksGP">
<a id="word" onclick="wButton(this.id); window.location='#container'" href="#">BRAND & CONSUMER MARKETING</a>
</div>
The only issue I have on IE is that the function enableTabButton is not working at all.

No version of Internet Explorer supports the use of forEach() on a NodeList, which is what's returned from querySelectorAll().
There is a polyfill available to fix this: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach#Polyfill

As you have tagged the question with keyword "jQuery" I am going to answer your question with jQuery :-)
Check the following solution if this fits your need. Works for me in IE11 as well as in all other more modern browsers.
"use strict";
var tabButtons = document.querySelectorAll('.navlinksGP > a');
function enableTabButton(buttonId) {
$(tabButtons).each(function() {
//console.log($(this).attr("id"));
if ($(this).attr("id") === buttonId) {
$(this).prop("disabled", true);
$(this).css("background-color", "#eeaf00");
$(this).css("color", "#ffffff");
} else {
$(this).prop("disabled", false);
$(this).css("background-color", "#ffffff");
$(this).css("color", "#eeaf00");
}
});
}
enableTabButton('word');
var player = document.getElementById('player');
function wButton(element) {
enableTabButton(element);
if (element === "word") {
player.innerHTML = "<h1 id=\"h1update\">Brand & Consumer Marketing</h1>";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="navlinksGP">
<a id="word" onclick="wButton(this.id); window.location='#container'" href="#">BRAND & CONSUMER MARKETING</a>
</div>

Related

Javascript removeEventListener doesn't work

So for a website I have a feature where If you click an image it shows it in a lightbox then on the second click it tracks the mouse movement to move the image. That works fine the problem is on the third click I want to toggle the mouse tracking on and off.
I've posted a simplified version of the code with a button instead of an image
<body>
<div id="myDIV"></p>
<button style="padding: 30px;" id="myBtn">Try it</button>
</div>
<p id="demo"></p>
<script>
document.addEventListener('click', buttonClick);
let scrollon =false;
function buttonClick(event) {
var elem = event.target,
elemID = elem.getAttribute('id'),
myBtn = document.getElementById('myBtn');
if (elemID == 'myBtn' && !scrollon){
event.preventDefault();
scrollon=true;
mine();
console.log('triggered')
}else
if (elemID == 'myBtn' && scrollon){
event.preventDefault();
scrollon=false;
mine();
console.log('untriggered')
}
}
function mine(){
if (scrollon == false){
myBtn.removeEventListener('mousemove',scroll);
return;
}
myBtn.addEventListener('mousemove',scroll);
function scroll(e){
document.getElementById("demo").innerHTML = Math.random(); //keeps going
//do something
}
}
</script>
This is a very good alternative code which works perfectly fine and is used very often.
So I only changed the mine() function.
function mine() {
if (scrollon == false) {
myBtn.onmousemove = null;
} else {
myBtn.onmousemove = function (e) {
document.getElementById("demo").innerHTML = Math.random(); //keeps going
//do something
};
}
}
Hope I could help!

Is there a way to trigger a function when a user tries to print in angular?

I am using a print element function to print out a view in my SPA. When the view changes the function runs and grabs the view. However, if the user changes something on the page it will not update and when you try to print, you get the same view as it was when the page first loaded. This is the function I'm using:
var printElement = function (elem, append, delimiter) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
$printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
if (append !== true) {
$printSection.innerHTML = "";
}
else if (append === true) {
if (typeof (delimiter) === "string") {
$printSection.innerHTML += delimiter;
}
else if (typeof (delimiter) === "object") {
$printSection.appendChlid(delimiter);
}
}
$printSection.appendChild(domClone);
};
My question is, can I trigger this function when someone uses the browser print function, such as Ctrl+P so that when they go to print the page, it will be updated?
You can make use of the default javascript events. Since you mentioned you are using jQuery:
$(document).bind("keydown keyup", function(e){
if(event.ctrlKey && event.keyCode == 80){
// CTRL+P was pressed.
}
});
I found a solution to my problem, it was answered by another question on stack overflow detect print. This is what I did:
var beforePrint = function () {
printElement(document.getElementById("print"));
};
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
printElement(document.getElementById("print"));
}
});
printElement(document.getElementById("print"));
window.onbeforeprint = beforePrint;
This covers IE, Chrome, Firefox, and Safari. The beforePrint works for IE and Firefox and matchMedia works for Safari and Chrome.

See if check box is clicked until it is clicked

I am seeing how I can make an Are You Human checkbox, but I am having a problem (Code At The End). I am trying to make it see if it is clicked until it is clicked. I tried onclick, but that is not working.
window.onload = function() {
var input = document.getElementById('ruhuman');
function check() {
if (input.checked) {
ruhuman.checked = true;
if (event.originalEvent === undefined) {
ruhuman.human = false;
} else {
ruhuman.human = true;
}
}
alert(ruhuman.human);
alert(ruhuman.checked);
}
input.onchange = check;
check();
}
<input type="checkbox" id="ruhuman" class="ruhuman" onclick="check()" required="required">
<label>R U Human?</label>
Edit: Thanks for your help! Finished product at http://ruhuman.github.io/.
To the people that answered I can put your github for your help!
originalEvent is JQuery, not JavaScript. A workaround is to test screenX and screenY -- if it's a human, these will have some value based on the checkbox position. Also, you can remove the onclick from your html and tie your click event like this:
document.getElementById ("ruhuman").addEventListener("click", function(e){
if (this.checked) {
ruhuman.checked = true;
if (e.screenX && e.screenY) {
ruhuman.human = true;
} else {
ruhuman.human = false;
}
}
console.log(ruhuman.human);
console.log(ruhuman.checked);
});
JS Fiddle Demo
This works: https://jsfiddle.net/rz4pmp5L/3/
var input = document.getElementById('ruhuman');
var ruhuman =
{
checked: false
};
function check()
{
if (input.checked)
{
ruhuman.checked = true;
}
alert(ruhuman.checked);
}
input.onchange = check;
check();
The problem was (at least) that ruhuman was not defined at all.

Background color for dropdowns doesn't work in IE. jQuery selectors not correct?

I have these dropdown menus:
#Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId, new SelectList(ChairList, "InterviewerId", "FullDetails"), new {#class = "ddlInterviewer" })
#Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].CofacilitatorId, new SelectList(NonChairList, "InterviewerId", "FullDetails"), new { #class = "ddlInterviewer" })
And this jQuery for changing the background-colors of the dropdown menus. This doesn't work in IE but does in chrome and firefox.
$(function () { // SET functions on document ready
$("#InterviewManagementFrm select").change(function () {
var text = $('option:selected', $(this)).text();
var lastChar = text.charAt(text.length - 1)
if (lastChar == 'A') {
$(this).removeClass("PreferredPreference");
$(this).addClass("AcceptedPreference");
}
else if (lastChar == 'P') {
$(this).removeClass("AcceptedPreference");
$(this).addClass("PreferredPreference");
}
});
$("#InterviewManagementFrm select").each(function () {
var text = $(this).text();
var lastChar = text.charAt(text.length - 2)
if (lastChar == 'A') {
$(this).addClass("AcceptedPreference");
}
else if (lastChar == 'P') {
$(this).addClass("PreferredPreference");
}
});
$("#InterviewManagementFrm option").each(function () {
var lastChar = this.text.substr(this.text.length - 1);
if (lastChar == 'A') {
if ($(this).is(':selected')) {
$(this).addClass("AcceptedPreference");
} else {
$(this).addClass("AcceptedPreference");
}
}
else if (lastChar == 'P') {
if ($(this).is(':selected')) {
$(this).addClass("PreferredPreference");
} else {
$(this).addClass("PreferredPreference");
}
}
});
}
Here is a screenshot of the html:
Could someone help me?
there are a lot of limitations as to what you can do with native drop down list in IE.
you will likely want to use some alternative that looks like a drop down list. there are a tone of really nice js dropdowns out there.
once you settle on one, you could write your own template for MVC.
good luck!
dear IE, why do you do su[k so much :(
my solution was to add a message across the top of all my sites that explains to users why they need something else with links to chrome and FF ;)

Simple JQuery working in some areas, not in others

After I added a slideshow to the site I am working on, some web components that use Jquery stopped working. However the newly added slideshow that also uses JQuery works as expected.
After some debugging, I found out exactly what JQuery is working and what isn't from the code below. I added a comment to my code to indicate that point.
I am importing my jquery library in the header and the code below is the last code before the closing <body> tag.
<!--SLIDESHOW-->
$(document).ready(function() {
var options = {};
if (document.location.search) {
var array = document.location.search.split('=');
var param = array[0].replace('?', '');
var value = array[1];
if (param == 'animation') {
options.animation = value;
}
else if (param == 'type_navigation') {
if (value == 'dots_preview') {
$('.border_box').css({'marginBottom': '40px'});
options['dots'] = true;
options['preview'] = true;
}
else {
options[value] = true;
if (value == 'dots') $('.border_box').css({'marginBottom': '40px'});
}
}
}
$('.box_skitter_large').skitter(options);
// Highlight
$('pre.code').highlight({source:1, zebra:1, indent:'space', list:'ol'});
//**** everything above works, everything below this point does not! ****/
$(".expandButton").click(function(ev){
$(ev.target).closest(".company-container").find(".expand").css("height", "140px");
$(ev.target).closest(".company-container").find(".expand").toggle("fast");
});
$(".emailLink, .email-popup").click(function(e){
e.stopPropagation();
$(e.target).closest(".company-container").find(".expand").css("height", "140px");
$(e.target).closest(".company-container").find(".email-popup").show("fast");
$(e.target).closest(".company-container").find(".phone-popup").hide();
$(e.target).closest(".company-container").find(".address-popup").hide();
});
$(".addressLink, .address-popup").click(function(e){
e.stopPropagation();
$(e.target).closest(".company-container").find(".expand").css("height", "550px");
$(e.target).closest(".company-container").find(".address-popup").show("fast");
var address = $(e.target).closest(".company-container").find(".address").html(); //get address text
if(!($(e.target).closest(".company-container").find(".map").length)){ //check if it was loaded
$(e.target).closest(".company-container").find(".address-popup").html('<iframe class="map" style="margin-top:45px;" width="575" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q='+ address +' &aq=&ie=UTF8&hq=&hnear='+address+'&t=m&z=14&iwloc=A&output=embed"></iframe>');
}
$(e.target).closest(".company-container").find(".email-popup").hide();
$(e.target).closest(".company-container").find(".phone-popup").hide();
});
$(".phoneLink, .phone-popup").click(function(e){
e.stopPropagation();
$(e.target).closest(".company-container").find(".expand").css("height", "140px");
$(e.target).closest(".company-container").find(".phone-popup").show("fast");
$(e.target).closest(".company-container").find(".email-popup").hide();
$(e.target).closest(".company-container").find(".address-popup").hide();
});
$(document).click(function(e) {
if (!(e.target.class === "email-popup" || e.target.class === "phone-popup")) {
$(".email-popup, .phone-popup, .address-popup").hide("fast");
}
$(".expand").css("height","140px");
});
$(".tagKeyword").hover(function(){
$(this).css("background-color","#fff");
$(this).css("color","blue");
$(this).css("box-shadow","none");
});
$(".tagKeyword").mouseleave(function(){
$(this).css("background-color","#eee");
$(this).css("color","#556");
$(this).css("box-shadow","1px 1px 2px #ccc");
});
$(".search-container").hover(function(){
$(".search-container").css("background","url(./images/menu/menu-middle.png)");
});
$(".searchfield").Watermark("search");
});
Can you try this?
$(".expandButton").click(function() {
$(this).closest(".company-container").find(".expand").css("height", "140px");
$(this).closest(".company-container").find(".expand").toggle("fast");
});
This may not help at all, but I didn't see the need for ev here and to instead use this.
May be you need to double check ev variable:
ev = ev || window.event

Categories