I have 3 divs
<div class="box opacity1 red"></div>
<div class="box opacity.5 green"></div>
<div class="box opacity0 blue"></div>
I want to have jQuery look at the page, see these classes and then create three different classes.
opacity1{
opacity: 1
}
opacity.5{
opacity: 0.5
}
opacity0{
opacity: 0
}
So when a user adds a class, eg "opacity75" to an element. I want the jQuery script to find "opacity" and then find what number is attached to it, then use that number to create a matching css class eg. opacity75{opacity:0.75}
I have very little knowledge of JS. I need some help to start me off in the right direction.
This can save having loads of CSS classes.
var stylestring = "<style type=\"text/css\">";
$("div").each(function() {
$.each($(this).attr("class").split(" "), function () {
var class = this + " {";
//add style to string
class += "}";
stylestring += class;
});
});
stylestring += "</style>";
$(document.body).prepend($(stylestring));
This would be my approach to iterate through all classes used in divs all over the page and create the class, but you would need some kind of rule to build the style out of the actual class name at the point of //add style to string
I'm not sure how it is even possible to create CSS classes in jQuery but here is a piece of code that'll do what you're expecting
Edit
$(function() {
$('.opacity').each(function() {
$(this).css('opacity', $(this).data('opacity'));
});
});
And add data-opacity="XX" to your <div> tags.
JSFiddle
1) yor example, its not best way to set css via js
2) i think task is to set some styles to elements, so its not necessarily to create classes.
jquery can set styles to elements via .css("property","value") method
3) example of code, which might work
// get all elements which contains 'opacity' in class name
var opacityElems = $( "div[class*='opacity']" );
var elemClassName;
var elemOpacityValue;
// cycle through all this elements
opacityElems.each(function(i,elem) {
// write the class name of the current element as a string
elemClassName = $(elem).attr('class');
// remove first 7 simbols, so only last numbers left
elemOpacityValue = elemClassName.substring(7, elemClassName.length);
// because obtained in the previous one step is a string, then give her number
// ie "0.12" to 0.12
elemOpacityValue *= 1;
// set style to element
$(elem).css("opacity",elemOpacityValue);
})
p.s. i am sorry for the mistakes - English is not the native language
Related
I would like to display an increased number (starting with 1 and ending with 47) for each class called quiz_image.
The HTML looks kind of like this:
<div class="quiz_image">
Content here
</div>
<div class="quiz_image">
Content here
</div>
<div class="quiz_image">
Content here
</div>
In order to display the number before the class quiz_image, I have tried it like this:
var i = 1;
$('.quiz_image').before(i);
i++;
In my code above the number will not increase, since there is probably a loop needed and I have no idea how to start a loop in this case. I hope somebody can help out on this.
When you use jQuery to get a selector it will return an array of elements. So you'll want to loop through them. I would suggest with something like the jQuery .each() function, which natively provides you with a 0 based index, you could try something like:
$('.quiz_image').each(function(i){
$(this).before(i + 1); // add one so we dont start at 0
});
Loopin all quiz_image and use their index numbers
$('.quiz_image').each(function(index){
$(this).before(index+1);
});
Working Demo
before function in jQuery sets the content before the specified element , and it also accepts the function so we can do it like the below example.
index function Search for a given element from among the matched elements
$('.quiz_image').before(function(){
return $('.quiz_image').index(this)+1
});
Why do you want to change the class for each image?
Rather give each one an ID.
<div class="quiz_image"></div>
<script>
counter = 0;
var quiz_id = $(".quiz_image").prop("id");
$(".quiz_image").each(function(){
counter++;
quiz_id = quiz_id + counter
$(".quiz_image").prop("id",quiz_id);
});
Suppose I have the following html:
...
<div class="thinger">...</div>
<div class="thinger">...</div>
<div class="thinger">...</div>
...
I want to dynamically set the width of all of the thinger divs. I know that I can do it like this:
$(".thinger").css("width",someWidth);
This will result in html that looks like this:
<div class="thinger" style="width: 50px;">...</div>
<div class="thinger" style="width: 50px;">...</div>
<div class="thinger" style="width: 50px;">...</div>
I would prefer to have the resulting HTML look like this:
...
<style>
.thinger {
width: 50px;
}
</style>
...
<div class="thinger">...</div>
<div class="thinger">...</div>
<div class="thinger">...</div>
...
I looked around but didn't see a jQuery utility to add/update/modify existing css classes. Does this exist?
I know that I could add it manually using something like this:
var styleElement = document.createElement('style');
styleElement.type = "text/css";
styleElement.innerHTML = ".thinger {width:" + maxWidth + ";}";
document.getElementsByTagName('head')[0].appendChild(styleElement);
But I don't want to have to deal with browser inconsistencies and I want to make sure I am doing things "the jQuery way". Any reason to choose one method over the other?
You can create the style element and append it to the head as you would any other element in the DOM, however it's a waste of time.
The best method to use would be to setup your class rule in a stylesheet and add the class to those elements. This maintains a better separation of concerns which is beneficial for both code reuse and maintenance later on.
I can't setup the class rule in a stylesheet because I don't know what the width will be prior to runtime.
In this case the current method you have of using css() is the best available.
Well that is a whole process read Add Rules to Stylesheets with JavaScript
Interesting question, it would be good to test if there is any performance benefit for using one approach over the other.
$("<style>.thinger{width:" + maxWidth + ";}</style>").appendTo("head");
If you need to update the value over time you should not keep appending new style tags to the page. Instead you'd want to update the existing one with something like this:
http://jsfiddle.net/daniellmb/0u5ffasq/
$('button').click(function(e) {
// get the dynamic width setting
var maxWidth = $(e.target).text(),
newRule = '.thinger{width:' + maxWidth + ';}';
styleTag = $('#thinger-style');
if (styleTag.length) {
// update existing
styleTag.text(newRule);
} else {
// create for the first time
$('<style id="thinger-style">' + newRule + '</style>').appendTo("head");
}
});
Yes there is. You can add or remove classes with jQuery .addClass() and .removeClass() methods.
$('#myDiv').addClass('myFirstClass');
or
$('#myDiv').removeClass('myFirstClass');
You can also use .css() method to update the css of an element like:
$('.myFirstClass').css('width','100px');
I'm new to jquery and I'm trying to turn off a specific css sheet when a specific page loads. This is the code that I've been using and I'm not sure that it is correct.
if(location.pathname=="/mycart") >= 0){
$('link[rel=stylesheet][src~="/media/css/responsive.css"]').remove();
}
The problem might be that path name check... also, instead of removing, try disabling the stylesheet:
if (location.pathname.indexOf('/mycart') >= 0) {
$('link[href*="/media/css/responsive.css"]').prop('disable', true);
}
Edit: The ~= selector looks for a space deliminated word, so use the *= selector instead.
Update (full code)
<script>
$(function () {
if (location.pathname.indexOf('/mycart') >= 0) {
$('link[href*="/media/css/responsive.css"]').prop('disable', true);
}
});
</script>
Instead of complicating things with on the fly style-sheets "canceling" why don't you simply create a wrapper class around objects that change on your page and define two sets of selectors that apply in case the wrapper does or does not have a specific class.
Lets say this is your HTML code.
<div class="my_cart">
<!-- Lots of shiny elements defined inside your cart... -->
</div>
Now you simply add two sets of stylesheets depending on how you actually want to style your cart in different situations.
.my_cart input {
...
}
.my_cart p {
...
}
/* The following two selectors will be applied to .my_cart ONLY if it also has the .disabled class assigned to it. */
.my_cart.disabled input {
...
}
.my_cart.disabled p {
...
}
Now all you have to do is following.
$(document).ready(function(){
if(location.pathname == "/mycart"){
$('.my_cart').addClass('.disabled');
}
});
Simple as that.
I have created a view in Drupal. I'm using JavaScript to modify the CSS in each row. The script runs on the first row, but does not make the changes on the rest of rows from the view.
This is the script:
<script language="javascript" type="text/javascript">
window.onload = floatbr;
function floatbr() {
var f = document.getElementById('firstright') // Get div element
var s = document.getElementById('secondright') // Get div element
var w = document.getElementById('catwrapper') // Get div element
var sh = s.offsetHeight // secondright div height
var wh = w.offsetHeight // catwrapper div height
f.style.height = wh - sh + 'px'; }
</script>
I'm using it from this page: http://agsone.100webcustomers.com/floatbottom.php
having the script in the page once does not do the trick.
having the script in the view footer and repeating the script does not work.
The link to the jSfiddle with HTML, CSS and JavaScript is the following one: http://jsfiddle.net/YTN3K/.
Drupal provides and already uses jQuery, so you should use it too. Drupal has its own way to manage JavaScript and comes with some additional JavaScript API, mainly to handle passing variables from PHP to JavaScript properly, register script to run on page load and content addition, etc.
jQuery is well documented and popular, so finding documentation, tutorial and howto is easy. Its own documentation page is a good start. But it requires basic understanding of what an XHTML document is and how it is structured.
It's hard to tell from your question and the markup you've linked to exactly what you're trying to do, so here's some general information to get you going:
The function you're currently using, getElementById, returns a single element: The one on the page with that id value. (id values must be unique on the page.)
To deal with multiple elements, you have several options. Two of the most popular:
You can start with a given element and then use its childNodes, firstChild, nextSibling, and similar properties to navigate from it to other elements nearby.
You can use getElementsByTagName (on the document or on an element) to find all elements within that container (including ones several levels down) that have a given tag. For instance, document.getElementsByTagName("p") gives you a NodeList of all paragraphs on the page.
These are properties and methods of the "DOM" (the Document Object Model), which is the tree of elements and associated information the browser creates when parsing and rendering your HTML.
References:
DOM2 Core
DOM2 HTML bindings
DOM3 Core
HTML5 Specification's DOM info
Here's an example showing some very basic operations (live copy):
HTML:
<div id="justOneDiv">I'm the <code>justOneDiv</code> element. I'm unique on the page. JavaScript code on the page turned me red.</div>
<div id="container">I'm a container called "container" with <span>various</span> <code>span</code> elements. <span>Code</span> on the <span>page</span> has made all of the <code>span</code> elements in this container <span>bold</span>.</div>
<div>I'm a container with <span>various</span> <code>span</code> elements. <span>Note</span> that the <code>span</code> elements are <span>not</span> bold, because I'm <span>not</span> in the container above.</div>
<div>I'm a <code>div</code> with no class.</div>
<div class="foo">I'm a <code>div</code> with class "foo". Code on the page turned me blue.</div>
<div class="bar">I'm a <code>div</code> with class "bar". Code on the page turned me green.</div>
<div>Another classless <code>div</code></div>
<div class="foo other">Another "foo", also with class "other"</div>
<div class="bar">Another "bar"</div>
<div>Another classless <code>div</code></div>
<div class="foo">Another "foo"</div>
<div class="bar test">Another "bar", also with class "test"</div>
<div>Another classless <code>div</code></div>
<div class="foo">Another "foo"</div>
<div class="bar">Another "bar"</div>
<div>Another classless <code>div</code></div>
<div class="foo">Another "foo"</div>
<div class="bar">Another "bar"</div>
JavaScript:
(function() {
hookEvent(window, "load", go);
function go() {
var list, index, div, container;
// Get just the one element, turn it red
document.getElementById("justOneDiv").style.color = "red";
// Get the spans within the specific container
container = document.getElementById("container");
list = container.getElementsByTagName("span");
// Loop through making those spans bold
for (index = 0; index < list.length; ++index) {
list.item(index).style.fontWeight = "bold";
}
// Get a NodeList of all divs on the page
list = document.getElementsByTagName("div");
// Loop it, turning "foo"s blue and "bar"s green
for (index = 0; index < list.length; ++index) {
div = list.item(index);
if (/\bfoo\b/.test(div.className)) {
div.style.color = "blue";
}
else if (/\bbar\b/.test(div.className)) {
div.style.color = "green";
}
}
}
function hookEvent(element, eventName, handler) {
// Very quick-and-dirty, recommend using a proper library,
// this is just for the purposes of the example.
if (typeof element.addEventListener !== "undefined") {
element.addEventListener(eventName, handler, false);
}
else if (typeof element.attachEvent !== "undefined") {
element.attachEvent("on" + eventName, handler);
}
else {
element["on" + eventName] = handler;
}
}
})();
Side note: The operations above can be made dramatically simpler by leveraging the utility functionality provided by any decent JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others.
For example, using that same HTML, here's the JavaScript code using jQuery for the same result (live copy):
jQuery(function($) {
// Get just the one element, turn it red
$("#justOneDiv").css("color", "red");
// Get the spans within the specific container
// Loop through making those spans bold
$("#container span").css("font-weight", "bold");
// Turn all divs with the class "foo" blue
$("div.foo").css("color", "blue");
// Turn all divs with the class "bar" green
$("div.bar").css("color", "green");
});
The DOM is the official API; libraries like jQuery provide alternate or enhanced APIs. They're very useful and powerful, but I would recommend having some understanding of the DOM itself, even if you use a library and end up rarely writing code directly to the DOM API.
I have this jQuery and I'm changing styles in it but I've heard that the correct way to do it is to create a separate style and just replace classes with jQuery. Can you explain me how to do it correctly:
$('.corpo_buttons_asia').click(function() {
$('.info').css('visibility', 'hidden');
$('.info2').css('visibility', 'visible');
$(this).css('z-index', '20');
$(this).css('background-color', 'rgb(23,55,94)');
$(this).css('color', '#FFF');
$('.corpo_buttons_global').css('background-color', 'rgb(197,197,197)');
$('.corpo_buttons_global').css('color', '#383838');
});
$('.corpo_buttons_global').click(function() {
$('.info').css('visibility', 'visible');
$('.info2').css('visibility', 'hidden');
$(this).css('background-color', 'rgb(23,55,94)');
$(this).css('color', '#FFF');
$('.corpo_buttons_asia').css('z-index', '2');
$('.corpo_buttons_asia').css('background-color', 'rgb(197,197,197)');
$('.corpo_buttons_asia').css('color', '#383838');
});
So instead of using .css() all the time I can create another class and just replace it with jQuery.
To do this efficiently using jQuery, you can chain it like so:
$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');
For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')):
var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');
Also (since there is a js tag), if you wanted to do it in vanilla js:
For modern browsers (See this to see which browsers I'm calling modern)
(assuming one element with class theClassThatsThereNow)
var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');
Or older browsers:
var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');
You may use this simple plugin:
(function ($) {
$.fn.replaceClass = function (pFromClass, pToClass) {
return this.removeClass(pFromClass).addClass(pToClass);
};
}(jQuery));
Usage:
$('.divFoo').replaceClass('colored','blackAndWhite');
Before:
<div class="divFoo colored"></div>
After:
<div class="divFoo blackAndWhite"></div>
Note: you may use various space separated classes.
Sometimes when you have multiple classes and you really need to overwrite all of them, it's easiest to use jQuery's .attr() to overwrite the class attribute:
$('#myElement').attr('class', 'new-class1 new-class2 new-class3');
Starting with the HTML fragment:
<div class='helpTop ...
use the javaScript fragment:
$(...).toggleClass('helpTop').toggleClass('helpBottom');
In jquery to replace a class with another you can use jqueryUI SwitchClass option
$("#YourID").switchClass("old-class-here", "new-class-here");
You'd need to create a class with CSS -
.greenclass {color:green;}
Then you could add that to elements with
$('selector').addClass("greenclass");
and remove it with -
$('selector').removeClass("greenclass");
You can use .removeClass and .addClass. More in http://api.jquery.com.
You can use jQuery methods .hasClass(), .addClass(), and .removeClass() to manipulate which classes are applied to your elements. Just define different classes and add/remove them as necessary.
Create a class in your CSS file:
.active {
z-index: 20;
background: rgb(23,55,94)
color: #fff;
}
Then in your jQuery
$(this).addClass("active");
you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...) just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");
jQuery.fn.replaceClass = function(sSearch, sReplace) {
return this.each(function() {
var s = (' ' + this.className + ' ').replace(
' ' + sSearch.trim() + ' ',
' ' + sReplace.trim() + ' '
);
this.className = s.substr(1, s.length - 2);
});
};
EDIT
This is my solution to replace one class with another (the jQuery way). Actually the other answers don't replace one class with another but add one class and remove another which technically is not the same at all.
Here is an example:
Markup before: <br class="el search-replace"><br class="el dont-search-replace">
js: jQuery('.el').remove('search-replace').add('replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace replaced">
With my solution
js: jQuery('.el').replaceClass('search-replace', 'replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace">
Imagine a string replace function in whatever language:
Search: "search-replace"
Replace: "replaced"
Subject: "dont-search-replace"
Result: "dont-search-replace"
Result (wrong but actually what the other solutions produce): "dont-search-replace replaced"
PS
If it's for sure that the class to add is not present and the class to remove is present for sure the most simple jQuery solution would be: jQuery('el').toggleClass('is-present-will-be-removed is-not-present-will-be-added')
PPS I'm totally aware that if your selector equals the class to remove the other solutions would work just fine jQuery('.search-replace').removeClass('search-replace').addClass('whatever').
But sometimes you work with more arbitrary collections.
I have used swap div to swap my video of self in thumbnail to main-video and vise versa.
I think this will help you to make a toggle between two div class.
numberId=0
function swapVideo(){
numberId++;
console.log(numberId)
if(numberId % 2 ==0){
$('#self-video').attr('class', 'main-video');
$('#trainer-video').attr('class', 'thumb-video');
}else{
$('#self-video').attr('class', 'thumb-video');
$('#trainer-video').attr('class', 'main-video');
}
}
numberId%2==0 help to keep track and perform a operation to make this toggle.