JS: Adding class to container, in an if-statement - javascript

I'm trying to make a small script with an if-statement: I want the condition to be, that if the class "page-title" contains "Welcome" it will add the class "excluded" to the element with the other class called "example". This is the js-code I've tried so far without luck:
<script>
$(document).ready(function(){
if(".page-title:contains('Welcome')"){
document.getElementsByClassName("example").addClass("excluded");
}
else{
}
});
</script>

here is a simple fix with js
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<h1 class="page-title">Welcome</h1>
<div class="example"> Example sample div</div>
<script type="text/javascript">
$(document).ready(function(){
if($('.page-title').text() == 'Welcome') {
$('.example').addClass('excluded');
}else{
// code here
}
});
</script>

You can implement that by selecting container with your class with jQuery, using text() method on it and trying to find "Welcome" in it. Try below code:
if($('.page-title').text().includes('Welcome')) {
// your code here
}

$(document).ready(function(){
if($('.page-title').text().indexOf('Welcome')){
$(".example").addClass("excluded");
}
});
You will need to decide which container/element you wish to add the 'excluded' class to, if you're finding that by using a class, you would write: $(".class-name-of-element-here").addClass("excluded"); or with an ID: $("#id_of_element_here").addClass("excluded");
Notice when searching for a container or element by ID, we use # and a class with .
Any example of this is: $('.page-title') you're looking for any element on the page with a class of page-title
When you're using addClass, you do not need to specify the . as a prefix, because we are specifically looking for a class.

There was 2 problems:
1: document.getElementsByClassName("example").addClass("excluded"); is a mix of javascript and jQuery.
javascript way: document.getElementsByClassName("example").classList.add("excluded");
jQuery way: $(".example").addClass("excluded");
2: if(".page-title:contains('Welcome')"){ is a valid if statement. use if ($(".page-title:contains('Welcome')")) {
$(document).ready(function() {
if ($(".page-title:contains('Welcome')")) {
$(".example").addClass("excluded");
} else {
}
});
$(document).ready(function() {
if ($(".page-title:contains('Welcome')")) {
$(".example").addClass("excluded");
} else {
}
});
.example.excluded {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page-title">Welcome to the world</div>
<div class="example">Is this excluded</div>

Related

jquery display none not working

Gurus, I am using Jquery to hide or display the fields based on the field value options. Previously I used hide and show function and it was working fine, but there is white space. So I changed to use jquery display none to hide the fields. however it doesn't work, please help, thank you! Below is my code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(
function(){
hideRating('initial');
}
);
function hideRating(scope){
if(scope=='initial'){
jQuery('[id$=CallSupportBeforeOutput]').style.display = "none";
jQuery('[id$=CallSupportBeforeQuestionLabel]').style.display = "none";
}
}
Here is the solution:
jQuery('#CallSupportBeforeOutput').css("display", "none");
jQuery('#CallSupportBeforeQuestionLabel').css("display", "none");
jQuery('[id$=CallSupportBeforeOutput]') return an array you need to provide index to change the style of elements. See below snippet.
jQuery(document).ready(
function(){
hideRating('initial');
}
);
function hideRating(scope){
if(scope=='initial'){
jQuery('[id$=CallSupportBeforeOutput]')[0].style.display = "none";
jQuery('[id$=CallSupportBeforeQuestionLabel]')[0].style.display = "none";}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-color: red"> visible content
<div id="CallSupportBeforeOutput">main content
</div>
<div id="CallSupportBeforeQuestionLabel">second content
</div>
</div>
Also you are mixing pure javascript with jquery by using style.display. You can use .css() jquery method to change the style if you don't want to provide index of elements.
<script type="text/javascript">
jQuery(document).ready(
function(){
hideRating('initial');
}
);
function hideRating(scope){
if(scope=='initial'){
jQuery('[id$=CallSupportBeforeOutput]').css("display", "none");
jQuery('[id$=CallSupportBeforeQuestionLabel]').css("display", "none");}
}
</script>
can you please try this!!
Both hide() function and style.display = 'none'; are same functionality. You have to check the CSS property. May be it will overwrite.
Use .css property instead of .style property as follows:-
jQuery('[id$=CallSupportBeforeOutput]').css("display", "none");
jQuery('[id$=CallSupportBeforeQuestionLabel]').css("display", "none");}

detect element where the function was called from

I need to know where my jQ function was called from...
In head:
function call_pl2(){
$(this).text('some text');
}
in Body:
<p> <script> call_pl2(); </script> </p>
<!-- OR -->
<div> <script> call_pl2(); </script> </div>
I got your point, I'm afraid you cannot get from the function the element that your js function is there, but each time that your function is called you can use another function and search your html content to see where this function is inside. I assume that this function is called ones from the html code when this is loaded.
Instead of trying to determine which element contains the the script tag (and, by extension, a particular call to call_pl2()) you could explicitly pass the containing element to call_pl2() as a parameter:
$(function() {
var call_p12 = function(element) {
if ($(element).is('p')) {
$(element).text('here is some text added to a paragraph');
}
if ($(element).is('div')) {
$(element).text('here is some text added to a div');
}
}
$('div, p').each(function() {
call_p12($(this));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p></p>
<div></div>
It would be relatively easy to modify the call_p12() function to swap in a more specific selector in the jQuery is(). For example is('.someclass') to check for a class value instead of a tag name.

How to use the title attribute of a div to add a class?

I'm trying to add a class to a div by using the title attribute. Currently the alert is correct. However the class isn't added.
JS Part:
function index(clicked_id){
alert(clicked_id);
$('#sticky').attr("title", +clicked_id).addClass("glow");
}
HTML Part:
<div id="sticky" class="" title='sticky1' onclick='index(this.title)'</div>"
I don't know if I got your question right but I understood that you want to filter|find you div by the title. So maybe this code will help you:
function index(clicked_id){
alert(clicked_id);
$('#sticky [title="' + clicked_id + '"]').addClass("glow");
}
This is how I would do it:
$("[title*='sticky']").click(function(){
$(this).addClass("glow");
});
Here is the JSFiddle demo
Why do you need to do it like that? Can't you just set the class on the element clicked?
JavaScript
function index(el){
$(el).addClass("glow");
}
HTML
<div id="sticky" onclick='index(this)'></div>
Instead just pass this:
onclick='index(this)'
now in the function:
function index(el){
var e = $(el).attr('title');
$('#sticky[title="'+e+'"]').addClass("glow");
}
As the element itself is the target one then just use this:
function index(el){
$(el).addClass("glow");
}
or better to go unobtrusive, remove the inline event handler and use this way:
$('#sticky').on('click', function(e){
$(this).addClass("glow");
});
js at Question returns expected results. Missing closing > at html #sticky <div> tag at
onclick="index(this.title)"
following onclick attribute . Additionally,
+
should be removed at
+clicked_id
at .attr() setting title . javascript + operator attempting to convert clicked_id String to Number when placed before string
function index(clicked_id){
alert(clicked_id);
$('#sticky').attr("title", clicked_id).addClass("glow");
}
.glow {
color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="sticky" class="" title="sticky1" onclick="index(this.title)">click</div>

hide one div when another is showing in jQuery?

I am trying to hide a div when another one is visible.
I have div 1 and div 2.
If div 2 is showing then div 1 should hide and if div 2 is not showing then div 1 should be visible/unhide.
The function would need to be function/document ready upon page load.
I've tried this but I'm not having any luck, can someone please show me how I can do this.
<script>
window.onLoad(function () {
if ($('.div2').is(":visible")) {
$(".div1").fadeOut(fast);
} else if ($('.div2').is(":hidden")) {
$('.div1').fadeIn(fast);
}
});
</script>
Add a class of hidden to each div, then toggle between that class using jQuery. By the way, window.onload is not a function, it expects a string like window.onload = function() {}. Also, put fast in quotations. I don't know if that's required, but that's how jQuery says to do it.
<div class="div1"></div>
<div class="div2 hidden"></div>
.hidden { display: none }
$(document).ready(function() {
if($(".div1").hasClass("hidden")) {
$(".div2").fadeIn("fast");
}
else if($(".div2").hasClass("hidden")) {
$(".div1").fadeIn("fast");
}
});
You should pass a string to the .fadeIn() and .fadeOut() methods.
Instead of .fadeIn(fast) it'll be .fadeIn("fast"). Same for .fadeOut().
And in general since you're already using jQuery it's better to wrap your code like this:
$(function () {
// Code goes here
});
It looks like you're using jquery selectors (a javascript library). If you're going to use jquery make sure the library is loaded properly by including it in the document header (google makes this easy by hosting it for you <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>)
With jQuery loaded you can do it like this
$(document).ready(function(){
if ($('.div1').is(":visible")) {
$('div2').hide();
}
else if ($('.div2').is(":visible")) {
$('div1').hide();
}
});
WORKING EXAMPLE: http://jsfiddle.net/HVDHC/ - just change display:none from div 2 to div 1 and click 'run' to see it alternate.
You can use setTimeout or setInterval to track if these divs exists
$(function() {
var interval = window.setInterval(function() {
if($('#div2').hasClass('showing')) {
$('#div1').fadeOut('fast');
}
if($('#div2').hasClass('hidden')) {
$('#div1').fadeIn('fast');
}
}, 100);
// when some time u don't want to track it
// window.clearInterval(interval)
})
for better performance
var div1 = $('#div1')
, div2 = $('#div2')
var interval ....
// same as pre code

changing image src onClick without using attr

Is there something wrong with this code? I am trying to do the simple action of changing the src of an img named "midimg" upon mouse-click. It's not working and i don't know why
<script type="javascript">
function buttonInCompany()
{
$('#desc').load('incompany.html');
document.images["midimg"].src="http://cageme.herokuapp.com/css/mrcage.jpg";
}
</script>
<div onClick="buttonInCompany()">Everything is cage's cage.<br><br></div>
<img name="midimg" src="http://3.bp.blogspot.com/-BdfyYy_Y0gY/UP_3y3F2RDI/AAAAAAAAC-Q/eHPCltO8bG8/s1600/TomEngelsnicolas+thing.jpg">
Do you need the jQuery line? I just dropped it, than it works as expected.
function buttonInCompany()
{
document.images["midimg"].src="http://cageme.herokuapp.com/css/mrcage.jpg";
}
Seeing as how you are apparently already using a js framework (I assume jQuery), why not do it a more proper way to begin with?
<script type="text/javascript">
function buttonInCompany()
{
$('#desc').load('incompany.html');
$('#midimg').attr("src","http://cageme.herokuapp.com/css/mrcage.jpg");
}
$(document).ready(function() {
$("#someID").click(function() {
buttonInCompany();
});
});
</script>
<div id='someID'>Everything is cage's cage.<br><br></div>
<img id="midimg" src="http://3.bp.blogspot.com/-BdfyYy_Y0gY/UP_3y3F2RDI/AAAAAAAAC-Q/eHPCltO8bG8/s1600/TomEngelsnicolas+thing.jpg">

Categories

Resources