I was wondering if anyone knew how I can change background images based on the specific ID that the user selects. I am essentially making a game where people select the right option and the images change based on the right answer/wrong answer. I tried to create a div on my HTML but I have no clue what I would do for the javascript because of my set system already.
Heres my code:
https://codepen.io/tdodia/pen/yLgMgRO
const textElement = document.getElementById('text')
const textElement = document.getElementById('text')
const optionButtonsElement = document.getElementById('option-buttons')
let state = {}
Also sorry, I had no real clue how to give correct context on the code so
i think the best bet is to look at the codepen link.
Sorry and thank you!
Tay.jis, Have made a few changes ->
You need to dynamically change the image source on button click, that will do the trick for you.
document.getElementById('myImage').src = textNodes[textNodeIndex]['url']
Also,
add a new key "url" in your object with the image you want.
Check the implementation->
https://codepen.io/raishavhanspal/pen/PoWmGVP
Related
Im very new to this and have reviewed other posts similar to this question. However, I'm finding that those solutions don't work for me.
Background: I'm working in Wix's Velo platform for Javascript. (forgive me if that's not the right technical terminology here)
My goal: When my website home page loads, I want one of the text boxes on the page (#text45) to NOT be visible until 5 seconds have passed. Then, when box #text45 is visible, I want another plain box (#box2) to turn to hidden.
I have found some examples like the one below: (not all code has been pasted and I realize some elements like div1 would need to change to my specific element names)
document.getElementById("div1").style.visibility = "visible";
}
setTimeout("showIt()", 5000);
However, I get an error code: Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.
When researching this, I found out that Velo cannot access the dom and elements can only be accessed via "$w".
Would someone be kind enough to set me in the right direction on how to accomplish the "goal" above? I would really appreciate it! Thank you in advance.
Here's how you would do it. Note, that it's good practice to change the IDs of your elements to more descriptive names, but I've stuck with the names you provided in your question.
Start by setting #text45 to hidden in using the Properties & Events panel.
Then use this code (note that your page might already have an onReady. If it's there an you're not using it yet, delete all the code on the page and replace it with this):
$w.onReady( () => {
setTimeout(() => {
$w('#text45').show();
$w('#box2').hide();
}, 5000)
} );
I want to take the logo of google.com and rotate it, not big deal and nothing really important, I just wanna learn JS in a fun way.
When I use the select element tool (Ctrl+Shift+c in chrome) I get that logo's id is "logo", so I'm trying this way:
const logo = document.getElementById("logo");
But I get this everytime I try:
undefined
I'd appreciate any help, TY <3
You need to target it's class, id or an attribute. Assuming you're talking about Google's default search homepage, the class seems to be using a dynamic value (you can still target using that value but your code will not work if you try to run it again when the values have changed) so you could target it's alt attribute instead and use the transform rotate() css property on it like this:
const logo = document.querySelector('img[alt="Google"]');
logo.style.transform = "rotate(180deg)";
The above two lines should rotate the Google logo if you run it in the browser console.
I'm assuming you entered that in the JS console.
The result of the const logo = ... statement is undefined, but that doesn't mean the const didn't get assigned (though in case the element doesn't exist, then logo did get assigned undefined...).
If the element does exist and you follow up with logo.style.transform = 'rotate(90deg)', it should work out fine.
As an aside, document.querySelector("img[alt=Google]") may be more bullet-proof for Google's front page.
See:
I currently take baby steps in JS development and coded the following link adder:
const button = document.getElementById('button')
const listdiv = document.querySelector('.listdiv')
button.addEventListener('click', function(){
let input = document.getElementById('text').value
let createA = document.createElement('a')
createA.setAttribute('href', input)
let linkDescr = document.createTextNode(input)
createA.appendChild(linkDescr)
listdiv.appendChild(createA)
})
The order of instruction is this:
Get the value of the text box
Create <a>
Set <a>'s link description
Set href
add <a>'s description to <a>
And then add all of <a> to the pre-existing Div..
So far so good. But, why is it that when we set href, it gets automatically added to <a>, but we have to take an extra step to add the link's description? Isn't let linkDescr = document.createTextNode(input) supposed to add the description automatically as well? My theory is that the commands are different in that we directly set an attribute of <a> for one, but create a variable on the other; and something need's to be done first with this variable. Variables don't just do anything by themselves. Please educate me on my logic. Also feel free to propose code changes/suggestions/flaws.
Thank you
There are often multiple ways to do things.
For example, the href can be added like this:
createA.href = input;
So then the description can also be added as a property.
createA.textContent = input;
The API simply gives us the choice. Appending a text node may make more sense in some cases, like when you're relocating an existing node.
In your case, you're creating a new text node. This is an object that is independent of any other part of the DOM tree, so it doesn't do anything until you insert it in the position where you want it, like inside the new a element.
I'm looking for a solution that will allow me to display a div when I click on a single link (which will change the way css style) with variable content (eg a sub-div with service1, service2, service3 ). This div will be displayed also propose several offers that will only display the div payment when one of these offers will be selected.
It's maybe hard to explain (i'm not english so sorry for really noob level), so maybe with this image you will "understand" a little bit more:
http://image.noelshack.com/fichiers/2015/38/1442422045-fonctionnement.jpg
I confess to being a bit lost with JavaScript for this kind of thing. I know it's probably achievable, but how? :-(
Thank you for your help folks!
If you want to go the way with altering CSS with javascript, assuming you are not creating the variable content on the fly, have the divs css for display set to none.
#divID {
display = none;
}
Then set an event listener on your link to change the display style to block.
document.getElementById("linkID").addEventListener("click", function() {
document.getElementById("divID").style.display = "block";
}
Ok so I created a crude representation of what you asked without much effects. But the fiddle I created completely functions as you intended. If you click buttons on div 1 the content of div 2 gets updated. If you click anything on div2 the information is displayed in div3. Here is the example: Working Example
window.function1 = function(){
var edits = document.getElementById('2');
edits.style.background="aliceblue";
}
//SAMPLE CODE TO EDIT ANY ELEMENT BY REFERRING BY ID. CALL SUCH FUNCTION ONCLICK
Please check the example to understand it fully.
I've got a pretty simple problem whose solution turns out not to be that simple at all.
I want to add images in front of each option of a selectfield. To be more accurate, I want to add images to the picker it triggers, and also to the selectfield's current value.
For the sake of simplicity, I'll create a little example:
Let's say, you want a user to choose between one of the four playing card suits Diamonds, Hearts, Spades and Clubs. To support visual recognition, you want to prepend the corresponding symbol to each suit name, so it could look something like this:
My first choice of a sencha touch component, that enables selecting from a given set of options naturally was selectfield. Unfortunately, it only seems to be able to display pure text, and nothing more. After digging into the sencha touch sources, I finally came up with half a solution. Basically, I pass the selectfield a custom defaultPhonePickerConfig, in which the corresponding picker(that is used by the selectfield to display the options) gets assigned a custom itemTpl. The itemTpl does the rest, namely adding some html to display the image:
defaultPhonePickerConfig: {
listeners: {
initialize: function() {
var slots = this.query('pickerslot');
Ext.each(slots, function(slot) {
slot.setItemTpl('<img src="someImage.jpg"> {text}');
});
},
change: function() {
// reconstruct the selectfield's change handler,
// since it gets overwritten
var iconSelect = Ext.Viewport.query('#IconSelect')[0];
iconSelect.onPickerChange.apply(iconSelect, arguments);
}
}
}
A working fiddle for this solution can be found here.
My solution isn't that bad, but there's a slight cosmetical problem, that's just not acceptable to me: The icons are only displayed in the picker (lower part of the screenshot above), but not the selectfield itself (upper, grayed out part) when the option was selected. And there seems to be no good way to add an icon to the selectfield's current value aswell.
And that's the main concern of my question: What good way is there to add an icon to both the picker's options and also to the selecfield's current value? Do I maybe just have to add relatively little code to my existing solution or should I take a whole nother approach?
Every contribution is appreciated. Thank you!
Update:
After some hacking around, I found a way (an ugly one) to prepend an icon to the selectfield itself. It is mostly based on brutal HTML DOM manipulation: I now also define event handlers for the selectfield itself (change and painted). On initialization and every time the value is changed, my handlers search the generated DOM for the underlying <input> and mess around with it. (That bad boy is probably the reason why we can't assign HTML in the first place, since the framework changes its value attribute. And value on the other hand can only contain plain text.)
This is how I define the selectfield's listeners:
listeners: {
change: function () {
var pickerDOM = document.querySelector('#' + this.getId() + ' input[name="picker"]');
PickerIcons.app.prependIconToSelectfield(arguments[1], pickerDOM);
},
painted: function () {
// Initialize an icon on creation
var pickerDOM = document.querySelector('#' + this.getId() + ' input[name="picker"]');
PickerIcons.app.prependIconToSelectfield(this.getValue(), pickerDOM);
}
}
The corresponding function prependIconToSelectfield() just defines some CSS:
prependIconToSelectfield: function (optValue, domElement) {
var iconUrl = this.getIconUrl(optValue);
domElement.style.backgroundImage = 'url(' + iconUrl + ')';
domElement.style.backgroundSize = '20px 20px';
domElement.style.backgroundRepeat = 'no-repeat';
domElement.style.backgroundPosition = 'left center';
domElement.style.paddingLeft = '30px';
}
Check out this fiddle for a working example.
This is still no good solution to me, since doing this kind of hackish DOM manipulation is way too rogue for my taste. I don't know what the side effects of actively messing around in the DOM could be in bigger projects, and don't want to learn it the hard way. So, I'm still looking for a cleaner solution.
First kudos on working so hard sencha touch is extremely hard to manipulate when you try to do something out of the box. Having said that let me try & propose a solution for what you want.
A selectfield in sencha has the following DOM tag structure.
div.x-field-select
div.x-field-input
input.x-input-el
div.x-clear-icon
div.x-field-mask
Now concentrate on the x-clear-icon it is normally hidden since a selectfield does not need a clear button. First write a css class for it to show it(display: block). This would display it with an X button similar to text field & it will be positioned towards the right corner. You can through css position it to the left and on change of the select field you can change its background to what you want. It is not a very straight forward solution but i have tried it for a similar problem & it works. Judging from what you have done above i think you can do it. All the best.
Hope my solution helps.