jquery .each function conflicts when changing DOM - javascript

Does anyone have a clue why this function only works partially in both scenarios (with tampermonkey extension)
Html:
<div class="container">
<p>
<a onclick="alert('item clicked')" class="">Element to auto click</a>
Element to open in new tab
</p>
</div>
Version 1:
setTimeout(function(){
$('.container a[href*="telechargement"]').each(function() {
$(this).attr("target", "_blank"); //not working
console.log(this) // see image bellow
$(this).prev()[0].click(); //working
});
}, 1000);
Version 2 (almost identical):
setTimeout(function(){
$('.container a[href*="telechargement"]').each(function() {
$(this).attr("target", "_blank"); //working
console.log(this) // see image bellow (same result)
$(this).prev().click(); //not working
});
}, 1000);
The console returns target="_blank" in both scenarios, but on the first scenario the DOM has not changed, so there is no target attribute. Why does it behave like this?
It seems to work in fiddle so I might be looking in the wrong place https://jsfiddle.net/n71w52hy/2/
. Could this come from TamperMonkey? Any suggestion welcome.
Thanks hips.

Related

jQuery .on() not binding/refreshing correctly

In my HTML, I have a div:
<div id='layerList'>
</div>
In my JavaScript, I dynamically append several items to this div, for example:
$('#layerList').append("<a class='lays dropdown-item' href='#'> This is an example </a>");
So far, everything works fine. My menu is built dynamically.
When I click on the different menu items, I want to change the active state and do other things, but it's not working — the menu items don't change state. Below is the click event handler:
$("#layerList").on("click", '.lays', function () {
console.log("test") // this works, I can see it
$(".lays").removeClass("active"); // this does not work
$(this).addClass("active"); // this does not work
// other stuff, doesn't work
});
Note that this code works just fine if I add the menu items in my HTML (i.e., if I do not create them dynamically).
What am I doing wrong?
There are two ways of achieving the same effect.jQuery:You can achieve the same effect using the shorthand .click method on the jQuery prototype. Attaching the event listener to the document and filtering through children is slow and will keep getting slower as your page size increases. Let me show you the code I have used.
$(".lays").click(function(e) {
$(".lays")
.removeClass("active");
$(this)
.addClass("active");
// other stuff
return false;
});
.lays.active {
color: red;
}
<div id='layerList'>
<a class='lays dropdown-item' href='#'> This is an example </a><br><a class='lays dropdown-item' href='#'> This is an example </a>
</div>
Using the buit-in javascript DOM API:
If you want a faster solution that does not need external libs, then accessing the DOM API might be better for you. The syntax is longer than jQuery's and doesn't have method chaining
so you'll end up with a bit more code than jQuery.
[].slice.call(document.getElementsByClassName("lays")).forEach(function(element) {
element.addEventListener("click", function(event) {
[].slice.call(document.getElementsByClassName("lays")).forEach(function(element) {
element.classList.remove("active");
});
element.classList.add("active");
//other stuff
return false;
});
});
.lays.active {
color: red;
}
<div id='layerList'>
<a class='lays dropdown-item' href='#'> This is an example </a><br><a class='lays dropdown-item' href='#'> This is an example </a>
</div>
Using [].slice.call turns an iterable object into an Array.
If you wanted to add support for older browsers, then I recommend adding a polyfill for the Array.from method.
Anyway, the code does work, so I'm not sure what's happening on your computer. Have you tried using Incognito Mode or the Guest account on Chrome, or Safe Mode on Firefox? Check all your extensions, as it is working fine in my browser (Google Chrome) right now. Good luck to you! :)
try a this way $("#layerList").on("click", 'a.lays', function () {
$("#layerList").on("click", 'a.lays', function () {
$(".lays").removeClass("active");
$(this).addClass("active");
// other stuff
});

Can't click div in cordova

Helo!
I am creating a cordova app, and run in to the following issue on S4 Mini, android 4.2.2.
I have a div element
<div class="switch" id="switchOff" onclick="clicked()">
<img alt="switch off" src="img/70/switchOff.png" />
</div>
Theres no way I was able to react to a click event. I tried every possible way I know.
$('#switchOff').css('position', 'relative');
$('#switchOff').css('zIndex','10000');
var foo = document.getElementById("switchOff");
console.log('zindex: ' + $(foo).css('zIndex')); //gives it back, so it works
$('#switchOff').bind('click',function(){
alert('Bind is the winner');
});
foo.click = function(){
alert('Native click is the winner');
}
$(document).on('click','#switchOff',function(){
alert('Holaon');
});
document.getElementById("switchOff").addEventListener('click', function(){
alert('eventlistener is a winner');
}, false);
The most strange thing is that I can even change the attributes of that div, so the selector works, and its already loaded to the dom.
Another strange thing is that it works well on other devices. (motorola defy, xperia tablez-z, atrix).
I run out of ideas, can someone help with this?
where is your clicked() defined?
Did you wraped the whole code in the jquery ready listener like this?:
$(function(){
$('#switchOff').click(function(){
//do something
});
});

toggle two images on click

I'm trying to use someone's code from an earlier post that I posted on here, and in it, he provided a jsFiddle that shows how to toggle between two images.
I'm trying to replicate exactly what that person is doing, but it doesn't seem to work on my code:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$('#ellomatey').toggle(
function(){
$(this).attr('src', 'bgimage.png');
},
function(){
$(this).attr('src', 'redsquare.png');
});​
</script>
</head>
<body>
<img id="ellomatey" src="bgimage.png" />
</body>
</html>
Does anyone know what I'm doing wrong? I have a feeling that it's not calling the function correctly, but it seems to work on that person's example.
The other two answers talk about the actual problem, but they don't tell you how you get to discover that, this is where debugging comes into play.
console.log("before");
$('#ellomatey').toggle(
function(){
console.log("bgimage"); $(this).attr('src', 'bgimage.png');
},
function(){
console.log("redsquare"); $(this).attr('src', 'redsquare.png');
});​
console.log("after");
If you do this, you'll notice "before" and "after" in your console. That's okay. But when clicking on the image, you would expect the other console logs, which means that the toggle function isn't doing what you thought it would do.
You can somewhat suppose the heavily used function to work properly, so there must be something up with the selector. Let's inspect that.
console.log($('#ellomatey'));
Heh, what?! No elements.
And then you start to think why and then you'll discover you need to wait till the DOM loaded; supposing you would have some underlying background in how a webpage loads, which is a prerequisite for what you're doing.
Wrapping
$(document).ready(function() { ... });
around it does exactly that.
All it takes is a little understanding and some simple debug output...
Don't just mindlessly code supposing it'll work, but verify your assumptions while you do it.
You need to wrap your code in a document.ready call. The way you have it the code will try to run before the actual content of the page has loaded.
<script>
$(document).ready(function() {
$('#ellomatey').toggle(
function(){
$(this).attr('src', 'bgimage.png');
},
function(){
$(this).attr('src', 'redsquare.png');
});​
});
</script>
You're defining your toggle function for an element that doesn't exist yet in the document, so you should wrap the js code on window.load handler (assuming you want to wait the complete image load) or at document.ready event
I created a flexible toggle script:
jsBin demo
put the second image url inside an data attribute for your image:
<img id="ellomatey" src="img_1.jpg" data-src="img_2.jpg" />
and on click just call the 'swap' function!
$(function(){ // BTW, you were just missing this 'ready' function :)
function swap(){
var mem = this.src;
this.src = $(this).data('src');
$(this).data('src',mem);
}
$('#ellomatey').click( swap );
});
This snippet can also handle multiple elements by just nesting your elements:
$('#ellomatey, .button, #something').click( swap );
(Added also in the demo a pure JS version. Have fun!)

Dropdownlist change event not working in IE9

I have this piece of code, that just refuses to co-operate, I've tried to look over the syntax, tried .change, .click events, nothing works, I am trying to alert the user, if the function works, nothing.
Heres the Javascript code:
$('#ProductNamesList').change(function () {
alert('JQuery works!');
});
And the HTMLHelper that generates the drop down list
#Html.DropDownList("ProductNamesList", New SelectList(Model.ProductList))
Can someone please help? I can't test it in other browsers, due to our requirements here -.-
For the record, I am using jquery-1.6.4.js and jquery-ui-1.8.16.js
Try this
$(document).ready(function() {
$('#ProductNamesList').live('change', function (event) {
alert('JQuery works!');
});
});
Looking at your live demo, it seems the problem is with the use of name="#sel". The correct notation is id="sel".
If you insist on use of name attribute, use jQuery selector [name="sel"]. Also note that the hash sign is redundant in attribute value.
I don't see anything wrong with it, the following worked for me in Firefox and IE8 (don't have IE9 available here).
#Html.DropDownList("ProductNamesList", new SelectList(Model.ProductList))
<script type="text/javascript">
$('#ProductNamesList').change(function () {
alert('JQuery works!');
});
</script>
Is the masterpage hooked up properly, and the reference to jquery correct?
I have tried the following code and it works.
<form action="">
<select id="sel">
<option>AUDI</option>
<option>Axel</option>
<option>BCS</option>
<option>BIBO</option>
</select>
</form>
<p id=result>
And the javascript:
$(document).ready(function() {
$("#sel").change(function () {
alert("JQuery works!");
});
});
When I try it at your live demo, I am getting error $ is not defined. I have created a jsfiddle which also works fine.
http://jsfiddle.net/rtFUs/
So all you have to do is to make sure that you are adding jquery correctly and the id of the select box is "mySelectBoxId" and you reference it using #, for example $("#mySelectBoxId"), that's it.

jQuery .hover not working in Safari or Chrome

I am currently trying to make some jQuery hover effects render correctly in all browsers. For the moment, firefox, IE, opera all do what they are supposed to. However, Safari and Chrome do not.
The code looks like this:
<div id="button1">
<div id="work_title" class="title_james">
WORDS
</div>
</div>
<div id="button2">
<div id="work_title" class="title_mike">
MORE WORDS
</div>
</div>
and the script effecting it looks like this
<script>
$(function() {
$("#button2").hover(
function() {
$("#james").css('z-index', '100')
$(".title_mike").css('width', '590px')
}, function() {
$("#james").css('z-index', '')
$(".title_mike").css('width', '')
});
});​
$(function() {
$("#button1").hover(
function() {
$(".title_james").css('width', '785px')
}, function() {
$(".title_james").css('width', '')
});
});​
</script>
what I am trying to get it to do is change the css styles two elements on hover over two large areas of text..
I have tried the mouseenter .addClass and mouseleave .removeClass thing and that didn't work at all.. so when I got this to work in firefox I was all happy... then I did cross browser checking and I got sad again..
You can see it live in action at:
http://roboticmonsters.com/who
Using the dev tools in Chrome it says there is an invalid token at the end of each of the javascript functions. The IE dev tools shows an invalid token too, but it seems to ignore this and render correctly. Check your source and remove the token, if you can.
IE:
Chrome:
$.css takes an object:
$("#james").css({'z-index': '100'});
Note the curly braces and colon (not comma).
This is so you can specify several css rules in one:
$("#james").css({'z-index': '100', 'height': '100px'});
If you are getting the value of a css rule, just pass in the name as a string:
$("#james").css('z-index'); // returns 100
It's possibly because you are trying to bind to those events before the DOM has loaded.
I didn't have much time to give you an answer as to why it was broken, but the following works for me in chrome.
$(document).ready(function() {
$("#button2").hover(function() {
$("#james").css('z-index', '100');
$(".title_mike").css('width', '590px');
},
function() {
$("#james").css('z-index', '');
$(".title_mike").css('width', '');
}
);
$("#button1").hover(function() {
$(".title_james").css('width', '785px');
},
function() {
$(".title_james").css('width', '');
}
);
});
if just use the code below it works fine:
$("#button2").hover(
function() {
$("#james").css('z-index', '100')
$(".title_mike").css('width', '590px')
}, function() {
$("#james").css('z-index', '')
$(".title_mike").css('width', '')
});
Otherwise Chrome reports: Unexpected token ILLEGAL. To see this yourself, right-click on the page and choose inspect element. Click the small red x in the bottom right.
Update: actually your code works fine if you remove the illegal character as shown in #anothershubery's answer

Categories

Resources