Convert jQuery to pure JavaScript - javascript

I'm having problems trying to convert this piece of code from jQuery into pure JavaScript.
I've wrote everything down in a JSFiddle as example.
The script is
$(".button").click(function () {
$pageID = $(this).attr('name');
var htmlString = $('#' + $pageID).html();
$('#1').html(htmlString);
});
$(".button").click(function () {
$(".button").css('background-position', '0px 0px');
$(this).delay(50).css('background-position', '0px -40px');
});
$(document).ready(function () {
$("[name='page1']").trigger('click');
});
For the first block I've used
function changeNavigation(id){
document.getElementById('1').innerHTML=document.getElementById(id).innerHTML;
}
And in each <div id="button"> added onclick="changeNavigation(id);" replacing id with page1 page2 etc for their respective buttons.
Which seems to work fine. The problem is the second block of code.
I tried using
document.getElementById("button").style.background-position="0px -40px";
Changing the class to an id attribute, just to test it, but it doesn't work.
What could be the problem? Is it that pure JS doesn't support background-position?
Also, as last thing, is it possible to use .innerHTML to write JS code?
I've tried using both JS and jQuery to write Scripts and despite both writing the same exact thing, the written code didn't work with .innerHTML.

Try
style.backgroundPosition
instead of
style.background-position
Thanks to Anthony Grist.
You have used class not ID. So It would be something like
document.getElementsByClassName("button")[0].style.backgroundPosition="0px -40px"

The hyphen is not valid in property names in JavaScript. Therefore, the CSS property background-position is called backgroundPosition in JavaScript.

Related

Select partial ID name in javascript

I have an asp.net webform where I include the following script (on a separate .js file):
function pageLoad() {
var mpe = $find("mpeEmpresa");
mpe.add_shown(onShown);
$addHandler(document, "keydown", onKeyDown);
}
function onShown() {
var background = $find("mpeEmpresa")._backgroundElement;
background.onclick = function() {
$find("mpeEmpresa").hide();
}
}
Unfortunately, it won't work because asp.net 3.5 changes the elements id's. The only way I could get it to work is to use ctl00_ContentPlaceHolder1_empresaFilha_mpeEmpresa as the ID.
Sure I could use <%= mpeEmpresa.ClientID %> from the asp.net side, it would work but I'll have to pass that as a var to my external .js file and it's not exactly what I'm trying to accomplish.
I have searched on a few ways to select the element by it's ID name partially, but couldn't get any of them to work... Is there a guaranteed way?
I can see the JQuery tag on your question, so you can easily use this:
$('div[id*="mpeEmpresa"]')
As i know the ContentPlaceHolders are rendered as div.
Update:
If you need to select empresaFilha too so you can't use the above selector.
because $('div[id*="mpeEmpresa"]') select both of ctl00_ContentPlaceHolder1_empresaFilha and ctl00_ContentPlaceHolder1_empresaFilha_mpeEmpresa.
so you need to use this:
Select only mpeEmpresa:
$('div[id*="mpeEmpresa"]').css("background-color","blue");
Select only empresaFilha:
$('div[id*="mpeEmpresa"]').parent('div[id*="empresaFilha"]').css("background-color","red");
Or something like this, maybe this code isn't so optimized because i don't see your ASP code or rendered HTML so have to provide a general solution.
You can simply use this
var mpe=$('div[id$="mpeEmpresa"]');
or
var mpe=$find('div[id$="mpeEmpresa"]');

javascript versus jQuery: highlighting some text, at the same time as, changing visibility of other text

This javascript code from RoToRa does what I want:
http://jsbin.com/ayoqem/7/edit#javascript,html,live
What jQuery code will do the same task? Which is better?
Sure, if you don't need to use jQuery then the javascript you have already will do just fine. But if you are using jQuery then you can accomplish the same task with just 3 lines of code.
http://jsfiddle.net/RWzQT/1/
$(document).ready(function() {
$(".qa input[type=checkbox]").click(function() {
$(this).parent().parent('div').toggleClass('show_answer');
});
});​
Note, that I also removed your inline javascript (onclick="hlt_showhide(this)") from the HTML.
If you don't need jQuery, don't use it. jQuery is built on top of JavaScript.. so if you already have code in pure-JS, why do you want it in jQuery??
The jQuery equivalent of that will be very similar in terms of line by line flow, only it'll use jQuery's .parent() to select the parent element and .addClass() & .removeClass() to do those actions.
function hlt_showhide(checkbox) {
$checkbox = $(checked); // just to cache it really!
var qaDiv = $checkbox.parent().parent();
if ($checkbox.attr('checked')) {
qaDiv.addClass("show_answer");
} else {
qaDiv.removeClass("show_answer");
}
}
but frankly I dont see the point of using jQuery here! JS does the trick.

Cant get Bootstrap javascript to work?

I am new to rails.
I have this simple code:
<h1>Pages#home</h1>
<p>Find <a id="t" rel="tooltip" title="Click me!">me</a> in app/views/pages/home.html.erb</p>
And the pages.js.coffee file:
jQuery ->
$('a#t').tooltip(placement: 'bottom');
The tooltip still pops up at the top of the word.
What am I doing wrong?
Your HTML markup contains an error, look at your links title, it has '>' character which has to be escaped in HTML, use > instead.
The problem is with how you are using options.
Try this instead. Hope it works
$('a#t').tooltip('placement': 'bottom');
Two things:
That should be an object literal in the tooltip() method call.
If you've already activated the tooltip on the element, calling the tooltip() method again will fail to update the options.
Given that, try something like:
if ($('a#t').data('tooltip')) { // check for tooltip data first
$('a#t').data('tooltip').options.placement = 'bottom';
} else {
$('a#t').tooltip({placement: 'bottom'});
}
Disclaimer: I know neither Rails nor CoffeeScript, but I do know the above code works in JS.

Can't change background of div region using javascript?

This should be so simple, but I'm making heavy weather of it.
Div region set out as:
<div class="maincontent">
Stuff in my div
</div>
CSS for that div:
.maincontent{
height: 100%;
background-size: 100%;
margin-left:1%;
margin-right:1%;
font-size:16px;
}
Then I have:
onLoad=changeBackground();
But before that I have the function:
function changeBackground(){
document.getElementByAnything('maincontent').style.backgroundColor="yellow";
}
I know its making the call to the function because if I put an alert box in there that shows. But no matter what combination of getElementBy I can't make any changes to the background?
Please help as its driving me insane!
TIA
Have you tried giving your div an id and using document.getElementById('divId') instead? I think if you want to get the element by class you have to use jquery.
getElementById('maincontent')
and change your div to have an id="maincontent"
Try giving the element an id and doing document.getElementById and then do console.log in firebug or other developer tools and verify that you are actually getting a dom element back.
Once you have verified that you should then be able to switch the background color
You're trying to select the div using its class. This isn't quite as straightforward as getting it by id. Try this:
<div class="maincontent" id='mainContent'>
Stuff in my div
</div>
function changeBackground(){
document.getElementById('mainContent').style.backgroundColor="yellow";
}
You can see a working example here: JSFiddle
If you want to get the element using its class, I would recommend using Jquery or another library.
If you're using in line Javascript then use, instead:
onchange="changeBackground(this)"
And:
function changeBackground(elem){
elem.style.backgroundColor = "yellow";
}
Edited as I suddenly remembered you were discussing events based on div elements. As a div doesn't natively support the onchange event, I'd suggest amending your code to the following (though changing the event-type onmouseover to whatever event you find most appropriate):
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
};
JS Fiddle demo.
Also, to remove the events from in-line code, and to make the JavaScript more portable and less 'intrusive':
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
}
var maincontents = document.getElementsByClassName('maincontent');
for (var i=0,len=maincontents.length; i<len; i++){
maincontents[i].onmouseover = function(){
changeBackground(this);
}
}
JS Fiddle demo.
Bear in mind, though, that some browsers (such as Internet Explorer 8 and below) don't support getElementsByClassName().
I recommend using jQuery if you want to select a DOM by class name.
Put this code in your <head> part of your html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
and change your function to
function changeBackground() {
$(".maincontent").css("background-color","yellow");
}

Using javascript to insert id into list elements

I am messing around with a deck of cards that I made.I have it set up so that there is a method that spits out cards by suit into a list, so if I want spades I get a <ol> of all of the spades cards. I am now trying to give each <li> element an id depending on what card it is. ace will be <li id="ace"><img src="ace_spades.gif"/></li> king will be <li id="king"><img src="king_spades.gif"/></li> for example.The list is in order from top to bottom akqj1098765432 . I tried doing this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12)
{
$(document).ready(function(){
$("li").eq(counter).attr("id", card_id[counter])
});
counter++;
}
but it doesn't work. I have not really done anything with javascript before besides simple jquery stuff. What am I getting wrong here?
Try this:
$(document).ready(function(){
var card_id = ["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$.each(card_id, function(i,id){
$("li").eq(i).attr('id',id);
});
});
You should try to only have one $(document).ready() function and it's not necessary to use a while() loop.
I think you don't need to call $(document).ready() function in the while. Try this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12){
$("li").eq(counter).attr("id", card_id[counter]);
counter++;
}
You do not need the document ready function. Place your script just before </body> and after the jquery.js script. This is working for me.
Check working example at http://jsfiddle.net/H8MeG/2/
First of ID's in a webpage have to be unique. Some browsers might ignore id's of elements that have already been used. Other browsers might fail completely...
Second off. you shouldn't use .eq() like that.
You definitely shouldn't add 12 new $(document).ready() statements.
Here's a more reliable version and the example on jsfiddle
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$("#spades li").each(function(index){
$(this).attr("class", card_id[index]);
$(this).text(card_id[index]);
});
I also added $(this).text(card_id[index]); so you see it actually works. Try to uses classes for multiple elements that share the same characteristic.
why are you messing with ids at all?
you know that the first item is the ace, the second the king, and so on.
ol.getElementsByTagName('li')[12]='deuce'

Categories

Resources