How to change style of div #id that contain selected .class - javascript

I'm trying to change style of div #info_frame that contain class nazwa_klasy_display and I can't fix it.
$('.box').mouseenter(function() {
//show up scores
$( this ).children( '.scores' ).css( 'display', 'block' );
nazwa_klasy = $( this ).attr('class').split(' ')[1];
nazwa_klasy_display = nazwa_klasy.split('_')[1];
if ($('#info_frame').has(nazwa_klasy_display))
{
$('#info_frame .'+nazwa_klasy_display).style.display ="block";
}
});

you're mixing jQuery with plain Js:
either you use
/* chain a jQuery method, e.g. show() */
$('#info_frame.'+nazwa_klasy_display).show()
or
/* access to the dom node before using plain js */
$('#info_frame.'+nazwa_klasy_display).get(0).style.display = "block";

If my understanding is correct, you are looking for a <div> that has the id of info_frame and the class of nazwa_klasy_display then you do need to fix your CSS selector. you have a space in there when it shouldn't be.
$('#info_frame.'+nazwa_klasy_display)
the selector #info_frame .[nazwa_klasy_display] will be looking for anything that has the class nazwa_klasy_display that is a descendant of *#info_frame

$("#info_frame").hasClass('.'+nazwa_klasy_display).css('display','block');
try this

Related

Remove class from parent element javascript

I have a container that opens via an onclick function. I then have a cross within the container that should close the parent element however I receive a
TypeError: undefined is not an object (evaluating 'parent.id')
Code is here
<div class="post" onclick="postClick(el)">
...
...
</div>
JavaScript
function postClick(el) {
document.getElementById(el.id).classList.add("read");
}
function postClose(event) {
var parent = this.parentNode;
console.log(parent.id);
parent.id.classList.remove("read");
}
Use event.target to get the reference to the HTML element.
And you have an extra .id in the parent.id.classList expression.
function postClick(event) {
const el = event.target;
document.getElementById(el.id).classList.add("read");
}
function postClose(event) {
const el = event.target;
const parent = el.parentNode;
console.log(parent.id);
parent.classList.remove("read");
}
<div class="post" onclick="postClick(event)">
...
...
</div>
One way of doing this is using pure Javascript and bind the event listener like this
document.querySelector('#toggle').addEventListener('click', function (e) {
console.log(this.parentNode.classList.remove('read'))
});
div {
padding: 20px 50px;
}
div.read {
background-color: red;
}
<div class="read">
<button id="toggle">Remove Parent Class</button>
</div>
Jut use this and you are done : 😊
element.parentNode.classList.remove("class-name");
if the project is complex and needs interactivity more than often then you use jquery library for the interactivity.
//to remove class
$( "p" ).removeClass( "myClass yourClass" )
$("#div123").toggle(); //if you want to temp hide elements
as your code suggests the 'read' items must be disabled, you can toggle them once an event handler is wrapped over the toggle method. you can pass this or $(this) in case you want to do stuff with the owner of the function call.
well i agree some adept devs didnt like this answer, it will be surely of some help to some beginner dev in future who is looking for an alternative option to hide elements or remove classes

element properties in jQuery

i'm new to jQuery. so in javascript you can create a div and give it it's own properties like this :
var msgbubble = document.createElement('div');
msgbubble.marginTop="10px";
msgbubble.style.backgroundColor="#ccc";
is there is anyways i can create an element like this in jquery and how to append it.
Thanks.
Check this code snippet to create div element with some css properties and set other attributes using jQuery.
$(document).ready(function() {
let elem = $("div"); // create div element and reference it with `elem` variable
// Set css properties to created element
elem.css(
{
'background-color': 'red', 'marginTop': '50px',
'height': '200px', 'width': '200px'
}
);
// Set attribute to created element
elem.prop(
{
'id':'div1', 'class': 'myClass'
}
);
$('body').append(elem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
For more info on jQuery visit https://www.w3schools.com/jquery
Hope, this small code snippet works for you.. :) :)
A small example of creating a div, setting properties, and appending it:
var msgBubble = $('<div></div>');
// set css properties
msgBubble.css({
'margin-top': '10px',
'background': '#ccc'
});
// or set html attributes
msgBubble.attr({
'data-foo': 'bar'
});
// add some text so it actually has a height
msgBubble.text('message bubble');
$('span').append(msgBubble);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
With jQuery(html) you can pass html text, which will then create an element.
var element = jQuery('<div></div>');
And if passed a second argument for attributes, jQuery(html, attributes), it will use those and set them on the element.
var element = jQuery('<div></div>',{
css:{
marginTop:'10px',
backgroundColor:'#ccc'
}
});
To append you can use the various methods like append(), appendTo().
element.appendTo(document.body);
So if you wanted to create your element, set the styles, and append the element in one go you would combine all of these like so:
jQuery('<div></div>',{
css:{
marginTop:'10px',
backgroundColor:'#ccc'
},
text:"Some text to go into the element"
}).appendTo(document.body);
jQuery simply uses the .append() method, though it also has .appendTo(), which functions the same way, although the two are syntactically different.
$("span").append("Appended text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
Ass for the actual stylisation, that can be done directly through the .css() property:
el.css('margin-top', '10px');
el.css('background-color', '#ccc');
Hope this helps! :)

Limiting the jQuery search scope correctly?

I've stumbled up this code and I'm wondering if its just limiting the scope or selecting both of the elements at the same time.
container = jQuery("#test", parent.document);
jQuery("param[name=scale]", another.object)
Can anyone shed some light on this?
Edit: the full example:
<script type="text/javascript">
jQuery = parent.jQuery;
container = jQuery("#test", parent.document);
another = {
targetw: container.width()
};
function onEnd(){
container.slideUp();
}
function onStart(){
another.object = jQuery("object", document);
another.w = another.object.attr("width");
another.h = another.object.attr("height");
another.targeth = Math.floor(another.targetw * another.h / another.w);
jQuery("div>iframe",container).width(another.targetw);
jQuery("div>iframe",container).height(another.targeth);
another.object.css("width", another.targetw+"px");
another.object.css("height", another.targeth+"px");
another.object.attr("width", another.targetw);
another.object.attr("height", another.targeth);
jQuery("param[name=scale]",another.object).attr("value","exactfit");
another.object.parent().attr('style', function(i,s) { return s + 'background:none; width: '+another.targetw+'px !important; height: '+another.targeth+'px !important;' });
}
document.write('*snipped code*');
</script>
`
That appears to be the context argument from the jQuery selector jQuery(selector[,context]).
From http://api.jquery.com/jquery/
Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:
$( "div.foo" ).click(function() {
$( "span", this ).addClass( "bar" );
});
When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.
Internally, selector context is implemented with the .find() method, so $( "span", this ) is equivalent to $( this ).find( "span" ).
It is a child - parent selector. The search starts within the parent instead of the whole DOM.
$('childNode', parent)
It is same as
$(parent).find('childNode')
Considering container = jQuery("#test", parent.document);
As #test is an ID based selector just jQuery('#test') wont make any difference as IDs are unique across the DOM elements.

Javascript only recognizising inline style and not style set in head

I have simple JS function that toggles the DISPLAY of a DIV. The DIV display is set to 'none' by default. If I use an inline style to set the display, it works fine, but if I set the style in the head it only works after I run the function the second time. So it only sees that the display is set to none after the display is set in the function. It doesn't recognize that it is set in the CSS in the head. If I use an inline style, it works fine.
Also, if I change my conditional statement from:
if (OBJ.style.display == 'none')
to
if (OBJ.style.display = 'none')
Use window.getCurrentStyle or element.currentStyle in order to obtain style from the head or body. They're supported by different browsers so here's a cross-browser example:
function getStyle( elem, style ) {
var a = window.getComputedStyle,
b = elem.currentStyle;
if ( a ) return a( elem ).getPropertyValue( style );
else if ( b ) return b[ style ];
}
getStyle( document.getElementById('OBJ'), 'display' )
The style property of an element only contains the inline style, not inherited styles or styles from a style sheet.
You can use the offsetHeight property to check if the element has any size, as it is zero when the element is not visible.
if (OBJ.offsetHeight == 0) ...
Another suggestion is to use css classes:
css:
.hide{
display:none;
}
html:
<div id="mydiv" class="hide">hello world</div>
<button onclick="toggle();">toggle</button>
js:
function toggle(){
var obj = document.getElementById('mydiv');
if(obj.className == 'hide')
obj.className = '';
else
obj.className = 'hide'
}
http://jsfiddle.net/XBhMA/1/
Note this will only work if the element contains only one class. If it contains more, you will need to modify.

JQuery - work with divs

I want to set another class for the clicked menu-part. Clicking generates url with #NAME. Here is my menu:
<div id="head_menu">
<div name="order" id="menu_part">make order</div>
<div id="menu_part">portfolio</div>
<div id="menu_part">contacts</div>
<div id="menu_part">vacancies</div>
<div id="menu_part">about company</div>
</div>
I need to add class: 'menu_choosed' for clicked part. Here is my jquery-code:
$(document).ready(
function()
{
currentPage = window.location.hash;
$('#head_menu>div').each(
function()
{
if( currentPage == $(this).hash )
{
$(this).addClass("menu_choosed");
}
}
)
}
)
I really don't know, how to filter values :( Help, please.
The easy way:
$(document).ready(
function()
{
currentPage = window.location.hash;
$('#head_menu a[href=' + currentPage + '] div').addClass('menu_choosed');
}
);
There are a few problems with your HTML I would like to mention:
Nowadays, most people use lists (<ul>, mostly) for navigation.
Having a <div> inside an <a> is invalid if the <div> has display: block (default) and the <a> has display: inline (default).
One document may only have one element per ID. You currently have several elements with the menu_part id.
Using name for anchor points is not recommended. Prefer using ID's.
All IDs must be unique. You're currently repeating menu_part. I'd suggest removing the duplicate IDs. Give the nav links a class of "nav_link" and then use jquery to reference that class with an onclick event that changes the class to "menu_choosed".
Try this:
$(document).ready(
function()
{
var currentPage = window.location.hash;
$('#head_menu a div').each(
function()
{
if( currentPage == $(this).parent().attr("href") )
{
$(this).addClass("menu_choosed");
}
}
)
}
)
it should be $('#head_menu>a>div') I believe.
also, ids are supposed to be unique, so it could cause problems that you have multiple divs with the same id. you may want to change menu_part to a class.
You can use:
$("#head_menu").find("a[href=" + window.location.hash + "]").addClass('highlight')

Categories

Resources