Trying to pass parameters to CSS from JavaScript - javascript

I have started working on a poetry app for the iOS platform which highlights the relevant text as the recording plays (as selected by the user). The user will see a list of options to play the audio (i.e. starting line, ending line), and as the app plays the recording, the relevant line will also be highlighted. My question is this:
My CSS code which is responsible for highlighting the relevant text looks like this:
#container {
positioon:relative;
}
#highlight {
position:absolute;
width:75px;
height:75px;
top:75px;
left:75px;
background: rgba(255, 0, 0, 0.4);
}
The values for width, height, top, left, and background are not static, they are dynamic (i.e. they will differ for each line). Is there a way for me to pass these values to the CSS from the JavaScript function that is calling it (which would in turn, be pass to the JavaScript from Objective-C)? Just wondering.

May I propose a different solution? I hope this is a little easier than your current attempt.
If you have some HTML like this:
<div class="lyrics">
<div class="line">I went down to the demonstration</div>
<div class="line">To get my fair share of abuse</div>
<div class="line">Singing, We're gonna vent our frustration</div>
<div class="line">If we don't we're gonna blow a 50-amp fuse</div>
</div>
So that each 'line' is it's own element, then it makes it very easy for your code to cycle through the lyrics line by line at an interval. This could be song lyrics, sheet music, even audio captions...
As you cycle through the lines you can target each one and add and remove classes. You don't have to use the jQuery library, but I use it pretty extensively so you could do something like:
// before transition
$(this).removeClass('highlight');
$(this).next('.line').addClass('highlight');
Then in CSS just give the ".line.highlight" or ".lyrics .highlight" some style definitions:
.lyrics .highlight {
font-weight:bold;
background:#ccc;
}
Things like the width and height would then be inherited, and you could reference them by calling:
$(this).css('width');
jQuery - css() - http://api.jquery.com/css/
jQuery - next() - http://api.jquery.com/next/
jQuery - removeClass() - http://api.jquery.com/removeclass/
jQuery - addClass() - http://api.jquery.com/addclass/

yes, what you do is in your javascript, look up the value.
$("#highlight").width()
for example, will get you the actual width.

Use jQuery to get and manipulate CSS properties of elements, as detailed here

You can add css to an element using jquery:
$("highlight").css('width','200px');
and you can replace 'width' with any valid css property, as well as pass in multiple properties.

Related

Best approach in sliding image and appending some room for content

I'm working with a jquery and I have this image that is the main problem. I googled it but came up with nothing. Here is my content for example.
And when the guy(in the picture above) is being click I want it to slide to the left side and will looked like this. Please see image below.
So what I'm thinking is
1. using addClass and removeClass using jquery or
2. just use jquery .slide or toggle function?
If there's a solution as such how could it be done? Since I only know is using addClass tho. And also what I'm planning is when the image exceeds 800px then the girl(in the image) will be send to back of the guy image.
What you are trying to do is create a mask around the guy. The scope of this question is beyond masking. Most methods of masking don't have large browser support at this moment so posting more on this would be disingenuous. But worth googling otherwise you can use the transform property to move the picture to the left. But you won't get the results you are looking for..
But there is the option of masking the picture in Photoshop and saving it as a PNG. And then utilizing the translate CSS method to move the image to left. This is your best option. But the details of either of these methods are out of scope for this question.
Cut this guy from image and put in another div at needed position. Put blue box between those two images and use slide function. You can cut the guy from his head i think.
Basically you need to have an html structure like this:
<div id='container'>
<div id='couple'></div>
<div id='mask'></div>
</div>
Initially in your css:
#mask {
display: none;
}
And, of course, you have to align horizzontally this two div.
Your jquery will have a behavior like this:
$('#couple').on('click', slide);
var slide = function() {
$target = $('#container');
$mask = $('#mask');
$mask.fadeIn();
$target.animate({
left: "+=50"
}, 500, function() {
/* callback on end*/
});
}
For complete documentation of animate check api jquery.

Make div overflow its container to work with marquee.js

I have built a music player which loads songs from a database in a random order. I would like to display track info in an info panel. Because I do not know the length of artist/track names, I would like the info to scroll with a marquee effect if it's too big. I'm told browser implementations of the marquee tag are bad so I have got a jquery plugin to do that for me in a nice smooth way (I assume the auther knows why they're bad and has sorted it).
So far so good.
The trouble is the marquee doesnt work out whether it is needed, so I would like to run a check to see if it is necessary (ie if the length of the text warrants it or not) before calling it.
Now I'm sure the problem here is a simple css one but I cannot for the life of me figure it out - you know when you've been staring at something too long...
What I am attempting to do is call the marquee on an inner div if the contents of the inner div are bigger than the outer div but no matter what I do I can't seem to get my inner div to stretch horizontally beyond my outer div unless I set a fixed width (which isn't very helpful since I don't know the width of the content).
Here is my simplified HTML (wrapper contains some other stuff floated either side):
<div id="mplayerinfo_wrapper"><div id="mplayerinfo_trackinfo"><div id="ti_inner"></div></div></div>
Here is my simplified css:
#mplayerinfo_wrapper{
width:545px;
height:30px;
margin-top:32px;
display:inline-block;
float:left;
}
#mplayerinfo_trackinfo{
height:30px;
width:238px;
display:inline-block;
overflow:hidden;
float:left;
}
#ti_inner{
float:left;
height:30px;
width:auto;
}
I am then hoping to use jquery to get the width of both elements, compare them and if inner is bigger than outer, launch the marquee like so:
var owidth=$('#mplayerinfo_trackinfo').width();
var iwidth=$('#ti_inner').width();
if(iwidth>owidth){$('#ti_inner').marquee();};
If this can't be solved through css, is there away to get content width with jquery/javascript. Any ideas? Thanks in advance
Since you already know the width of the outer div, it may be easier to compare against that measurement rather that ask for that width dynamically. I've tried to re-create your simplified program and the problem I ran into was that the width() function only returned the default width of the div's, not the width as modified by css.
Your CSS looks appropriate for what you are trying to accomplish. I would try this for the comparison:
if ($('#mplayerinfo_trackinfo').innerWidth() < $('#ti_inner').outerWidth()) {
$('#ti_inner').marquee();
}
I have had better results when using JQuery's inner and outer measurements.
the ti_inner CSS needs to have
white-space: nowrap;
to prevent the div just increasing in height,
We can then check the widths to see if a marquee is required.
I prefer to check the scrollWidth and the offsetWidth of the outer mplayerinfo_trackinfo instead of comparing the width of the 2 separate divs, mainly so that and margins,borders or padding dont get in the way, but in this example it doesnt really matter.
Heres a sample on JSFiddle marquee if required
Sorry it's in mootools but I'm new to all this web stuff myself and have not used any JQuery but from what I've read it should be easy to swap.

Javascript style issue

I am using javascript to display the height of my current div.
This is an example of the effected area
//css
.test
{
height:1px;
}
#test1
{
margin:1px;
}
//html
<div id="test1" class="test"></div>
//javascript
var a = document.getElementById('test1');
a.style.height //how I access the style
Firebug says that the length of style is 0 and height is empty.
How can I access the correct height?
You need to look at the computed style, not the specified style. See Quirks mode's getstyle page which answers the question
Sometimes you'll want to see what styles the default document view has. For instance, you gave a paragraph an width of 50%, but how do you see how many pixels that is in your users' browser?
and it explains how to derive and use the getstyle function, though it's easier to use a library like jquery which provides a simple css function.
Try a.offsetHeight instead of a.style.height
jsfiddle demo
div height is dependent on its children. If its empty, it'll be 0.
The code you have to get height is correct, btw.
Check out the getComputedStyle method. It should do what you are looking for. Kinda lame, really, I wish this was handled better in the DOM.

JavaScript Cursor Change (and change back again)

I have this page that does some funky database stuff that takes a couple seconds to process, and in the meantime I'd like to set a "wait" cursor so the user doesn't flip out and keep clicking the button. I've looked at the
document.body.style.cursor = "wait"
thing, the problem with this is that it only works when the mouse is over the body of the page (i.e. still shows normal pointer if it's over a button). How can I set it so that no matter where the mouse is on the page, it shows a wait icon?
A second part to this question is, once it's done it's thing, how do I set it back? If I set it back to "default", this seems to override any "hover" cursor changes I had set in my CSS (so it no longer becomes a hand when over a specified object, etc.).
EDIT: the first answer works nicely, except in IE it doesn't refresh the cursor (so you notice the change of cursor type) until you actually move the cursor. Any fixes?
What I suggest is two things:
a) Better write a CSS like
body.waiting * { cursor: wait; }
b) Use the JS to handle the body class
/* when you need to wait */
document.body.className = 'waiting';
/* to remove the wait state */
document.body.className = ''; // could be empty or whatever you want
You might want to add the class instead of replace the whole class attribute, what I suggest is to use something like jQuery for that.
EDIT 2019: don't use jQuery for just this, use classList
The styling should be handled via CSS, as stated by W3C.com:
CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. ... The separation of HTML from CSS makes it easier to maintain sites, share style sheets across pages, and tailor pages to different environments. This is referred to as the separation of structure (or: content) from presentation.
As suggested by Tom Rogerro, add a line to your CSS file:
body.waiting * { cursor: wait; }
However, your script should not overwrite the entire list of class names. Tom suggested setting the class names via jQuery, but jQuery is unnecessary in this case. Simple Javascript can do this.
To add a class name 'waiting' to the document body:
document.body.classList.add('waiting');
To remove a class name 'waiting' from the document body:
document.body.classList.remove('waiting');
For your first problem, try using cursor: wait !important;.
For your second problem, the default cursor for elements is cursor: auto;, not cursor: default; or cursor: inherit;.
If you are happy using JQuery then a quick way to solve this would be to use:
$('*').css('cursor','wait')
I don't know how elegant this is but it has been working for me,
Not an answer to the question, but a way of achieving what is wanted.
Make a div (see class below) visible when you are loading.
ensures no element is accessible and dimmed display indicates this.
you can add an animated gif to indicate something is going on instead of the cursor.
.loading{
position:fixed;
height:100%;
width:100%;
left:0;
top:0;
cursor:wait;
background:#000;
opacity:.5;
z-index:999}
Any elements that don't inherit the cursor by default (such as buttons) will need to set the cursor to inherit:
someButton.style.cursor = 'inherit';
To go back to the default for an element (and not break things like :hover with a forced cursor), set it to an empty string:
document.body.style.cursor = '';
I tried everything but finally this jquery worked, especially if you want wait cursor over all elements including buttons and links.
define at the top of angular .ts file
declare var $: any;
and then where ever you want wait cursor:
$('*').css('cursor','wait');
and remove wait:
$('*').css('cursor','auto');
To fully replace the CSS toggling behaviour, we can simply use this inline:
<img
src=https://cdn.sstatic.net/Img/unified/sprites.svg
onmouseover="this.style.cursor = 'crosshair'"
>

want to change color at multiple places in one go !

My problem is I have couple of divs in my page. All have header of similar color. Now if I have to change the color(for example background color) of all divs, I have to make changes as many divs I have. Is it not possible to just change or say write the color code at one place (like in a variable) and the then use that variable as color value in the embedded styles to all those divs. Something like javascript entities.
If you need variables in CSS, you might want to look at CSS pre-compilers (is this the correct term?), such as Sass, which does this Server-side and eases the pains for having many different color repeated across multiple rulesets.
Otherwise, when developing, try splitting your CSS files into individual components, such as typography.css, color.css etc. to help better organise them. You'll still want to combine them after development is complete for better performance, but doing this does help keep things neater and tidier.
Lastly, you can always define large rules like this:
#header, #footer, #nav, #sidebar {
color: orange; /* I like orange! */
}
Which would reduce redundancy somewhat. Using Javascript for styling and presentation should only be kept as a last resort; there are always tools available to keep your CSS tidy; you only need to use them.
u can write some css and jquery to achive this
.color1
{
color:red;
background-color:green;
}
.color2
{
color:blue;
background-color:orange;
}
now on some event u can change classes. for example intitially u have
<div class="header color1">SOME TEXT HERE</div>
<div class="header color1">another header</div>
u can change this with jquery or even with javascript :)
$("#somebutton").live("click", function(){
$(".header").removeClass('color1');
$(".header").addClass('color2');
});
this will change color of both headers at click of button with id somebutton
How about setting the same class on all divs and set all common colors in there? That way you'd only have to change the color for that class.
I would suggest using jQuery or another javascript library, to do this.
Assign a class to the divs you wish to alter, and then use the following code (when giving them a clas of 'header-div')
$('.header-div').('background-color','#FF0000');
this will change ALL elements with the class of 'header-div'
Jquery solution
define all the divs with a specific class like
<div class="changeable"></div>
Then use jquery to change the background
$(".change").click(function() {
$(".changeable").css("background","#000");
});

Categories

Resources