I've got a list of links, all in the same class, each with a custom argument ("switch-text"). My script should copy the text of the custom argument to the text of each link and replace it ("Pick A" should become "Pick A Please").
It works fine with only 1 link, but when I add several, they all get switched to the first argument. ("Pick B" should be replaced by "Pick B Please", but it doesn't).
I could probably solve this using each(), but I'm preferably looking for a simple, single jQuery line that does it, and I'm baffled I haven't yet found out how to achieve this.
Can somebody help? Thanks!
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$(".switcher").text( $(".switcher").attr("switch-text") );
});
</script>
Pick A<br>
Pick B<br>
You should use each to go through all the elements, and use this to always act on the current one.
$(document).ready(function() {
$(".switcher").each(function(){
$(this).text( $(this).attr("switch-text") );
});
});
Demo
Without jQuery
you need:
Dean Edwards document ready
getElementsByClassName
Code:
readyList.push(function() {
var els = getElementsByClassName("switcher");
for ( var i = els.length; i--; ) {
els[i].innerHTML = els[i].getAttribute("switch-text");
}
});
And change Dean's script to execute functions on document.ready:
function init() {
// ...
// do stuff
for ( var i = 0; i < readyList.length; i++ ) {
if ( typeof readyList[i] === "function" ) {
readyList[i]();
}
}
//..
}
That's it. You've saved a lot of bandwidth. :)
Demo without jQuery
Related
<script>
function balanceRefresher() {
<b>Balance:
document.write(playerBalance)
</b>
}
setInterval(balanceRefresher, 1000);
</script>
Obviously, this isn't actual code, but what I'm trying to do is refresh variable 'playerBalance' in text. I have no idea what other way I could do this in, as I am an almost complete beginner to javascript.
document.write, does as the name suggests writes to the document, if you want to dynamically modify and element on the display then create a placeholder and then access the element and modify, for example, in your document create a placeholder:
<div id="any_id"></div>
Then in your javascript:
let el = document.getElementByID("any_id");
if ( el ) {
if ( el.hasChildNodes() ) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(document.createTextNode("your text"));
}
https://www.w3schools.com/jsref/met_document_getelementbyid.asp
look this example enter link description here
$( document ).ready(function() {
var i=1;
setInterval(function(){
$('p').html('');
$('p').append('<span id="add_here">'+i+'</span>');
i++;
}, 1000);
});
I'm a long-time procedural programmer now assigned to a web-app and studying jquery from a book. The exercise is to run some code on one div selected from a row of 4 <div>s using .each(). I attempted to store the div object that was clicked, then match it as the .each looped thru the 4 divs.
My following code works after trial and error, but the same $(this) seems to sometimes point to a div object, and sometimes to an event object.
How do you explain that behavior?
I understand that .context is deprecated. I tried .target but that didn't seem to work. Is there something else that I should be using?
My primary interest is to understand what is going on (question 1), so if you can provide an explanation and not just an alternative solution (question 2), I'd really appreciate it. Thank you in advance. Here are the code snippets:
<body>
<div id="header">
<h2>Jump for Joy Sale</h2>
</div>
<div id="main">
<div class="guess_box"><img src="images/jump1.jpg"/></div>
<div class="guess_box"><img src="images/jump2.jpg"/></div>
<div class="guess_box"><img src="images/jump3.jpg"/></div>
<div class="guess_box"><img src="images/jump4.jpg"/></div>
</div>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_script.js"></script>
</body>
Jscript
$(document).ready(function()
{
$(".guess_box").click(checkForCode);
function checkForCode()
{
var code_box = 2;
var discount_code = getRandomNum(1,100);
var clicked = $(this); // debugger says clicked is an event object
var iteration = 0;
$(".guess_box").each(function()
{
if ($(this).context === $(clicked).context) //act like event objs
{
if (iteration === code_box)
{
// clicked on correct box
$(this).addClass("discount"); //same $(this) acts like <div>
discount_msg = "<p>Your Code: CODE"+ discount_code +"</p>";
return(false);
}
}
else
{
if (iteration === code_box)
{
// if wrong box clicked, highlight the right one
$(this).addClass("no_discount");
discount_msg = "<p>Sorry, no discount this time</p>";
return(false);
}
}
iteration += 1;
});
$(".guess_box").unbind();
$(this).append(discount_msg); // don't worry about this line
} //checkForCode
}); //ready
The context of this depends on where and how it's used. if your function is called by an an event it will refer to the target of the event, otherwise it will refer to the object being called upon.
What youre seeing in your console is not this, or an event object, it's a jQuery object. If you want to inspect this you need to remove the jQuery wrapper function.
console.log(this);
Event example..
<div>click me</div>
$("div").click(function(){
// referring to the div itself
$(this).text("you clicked me");
// Note you can do it without jQuery as well
// this.innerHTML = "you clicked me";
});
object example
function something(){
this.something = "something";
this.doAThing = function(){
this.something = "something new";
}
}
var thing = new something();
thing.doAThing();
alert(thing.something);
Thanks to those that responded. As Pamblam indicated, I was confusing this and $(this). I replaced 2 lines in my code and it makes more sense:
clicked = $(this) becomes clicked = this
if ($(this).context === $(clicked).context) becomes
if (this === clicked)
I'm in a situation where I want to check if two elements (one is clicked and another one a reference) are the same, what I'm trying to do is:
$("#process li").click(function() {
currentElement = $(this);
referenceElement = $("#process li:first-child");
if (currentElement === referenceElement) {
$(".mark").removeClass("mark");
$(this).addClass("mark");
}
});
So what I want is to check if the clicked <li> is the first child of the ul#process and if so first remove a .mark class from another element and then add it to the clicked one. I don't get any working result - ideas anyone?
UPDATE:
Thanks you very much! This is my solution:
$("#processlist li").click(function() {
currentElement = $(this);
if (currentElement.is('li:first-child')) {
$(this).addClass("mark");
}
});
Now if I click on a , if it is the first child of this list, the class .mark is added - sweet!
Comparing objects in JS is very troublesome. The simplest way is to just pick a few key properties and compare those, eg:
if (currentElement.prop('id') === referenceElement.prop('id') {
// rest of your code...
}
However, given your use case you could use is:
if (currentElement.is('#process li:first-child')) {
// rest of your code...
}
Example fiddle
You need to extract the DOM element from the jQuery object. You can use the get method of jQuery for this.
e.g. if( currentElement.get( 0 ) === referenceElement.get( 0 ) )
I'm trying to change the "10" in the HTML below using jQuery:
<div id="ingredients">
<h2>Ingredients</h2>
<h4>Sugar: <span class="sugar">10</span></h4>
Here have been the iterations that I've gone through that have been unsuccessful:
$(document).ready(function() {
$('#ingredients.sugar').html("5");
});
and
$(document).ready(function() {
$('span[class=sugar]').html("5");
});
In addition, how would I store the value of "10" in a variable? I'm trying to do this:
var $sugar = $('#ingredients.sugar').html();
Would that work?
Thanks!
Henry
Try:
$(document).ready(function() {
$('#ingredients .sugar').html("5");
});
Notice the space between; this says look for a .sugar child from the #ingredients parent. You should also be able to do:
var val = $('#ingredients .sugar').html();
You have missed space in your selector, this will work:
$('#ingredients .sugar').html("5");
Here's a version with a simplified selector (don't need #ingredients), factory caching and update without using quotes (5 works fine).
// Document ready
$(function () {
var $sugar = $( '.sugar' ), // Cache jQuery factory
originalValue = $sugar.html(); // Cache original value
// Update value
$sugar.html( 5 );
});
I am creating a Safari extension that clears Outlook.com advertisements and other content. I have made two versions of the extension, one with CSS and one Javascript. However, there is a delay when removing the elements with Javascript. I was wondering is it possible to call a CSS file using Javascript so that it removes the elements quicker?
If anyone has made a Safari extension or is familiar with it, how can I make check box that will call a specific CSS file? For example, there is a CSS file called 'ads' and I have checkbox with the 'Key' ads and I want to be able to find a way so that I can call it when the checkbox has been checked.
I hope you understand what I am trying to say :) It is a bit difficult to write what I want to say.
Thanks.
This is the proxy.html file that calls the functions.
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
var data = new Object();
safari.application.addEventListener( "message", function( e ) {
if( e.name === "getData" ) {
data.advertisements = safari.extension.settings.getItem( "advertisements" );
};
}, false );
</script>
</head>
<body>
</body>
</html>
Here is the script.js file.
$(function() {
safari.self.addEventListener( "message", function( e ) {
if( e.name === "setData" ) {
handleEvents( e.message );
}
}, false );
safari.self.tab.dispatchMessage( "getData" );
function handleEvents( e ){
if (e.advertisements !='show') {
var customStyles = document.createElement('style');
customStyles.appendChild(document.createTextNode('#RightRailContainer {display: none !important;} .WithRightRail {right: 0 !important;}'));
document.documentElement.insertBefore(customStyles);
}
Yes you can. In JavaScript you can use a function to create DOM elements:
document.createElement("link"); // Create CSS element.
Then you can use .setAttribute(attr, value) to give attributes to the created element. You can do something like this:
var file=document.createElement("link");
file.setAttribute("rel", "stylesheet");
file.setAttribute("type", "text/css");
file.setAttribute("href", "main.css");
Note: You can also set the property directly doing file.[attr] = [value]. For example, this does the same thing as the above code:
var file=document.createElement("link");
file.rel = "stylesheet";
file.type = "text/css";
file.href = "main.css";