I am trying to determine if an image source contains a string when I click on the image. The images have the class .swap-color. I have the variable $current_swatch set to the image src attribute, and it tests successfully. My code is below. No matter what image I click on, I get the alert "Contains TB", even if TB isn't in the image src. What am I doing wrong?
<img src="/images/Swatch-TB.jpg" class="swap-color"/>
$("document").ready(function () {
$('.swap-color').click(function () {
//get the image src
var $current_swatch = $(this).attr('src');
//check if TB is in the src
if ($('$current_swatch:contains("TB")').length > 0 ) {
alert ('Contains TB');
} else {
alert ('Does not contain TB');
}
});
});
There's enough feedback that I'm going to go out on a limb and post an answer, even though the key to your question could be done in a comment.
The way to check for the contents is to use the JS native indexOf(), rather than the jQuery selector method in your code.
Here's some commented revisions to your code:
// Streamlined, conflict-safe document ready
jQuery(function ($) {
$('.swap-color').click(function() {
//get the image src
var $current_swatch = $(this).attr('src');
//check if TB is in the src
// Use JS native "indexOf" rather than jQuery
if ($current_swatch.indexOf('TB') > -1 ) {
alert ('Contains TB');
} else {
alert ('Does not contain TB');
}
});
});
For more information on different ways to check for a substring, check out this answer: Fastest way to check a string contain another substring in Javascript?
So, you're using the jQuery's contains method which checks if a selector contains a value. The problem is, $current_swatch is actually a string, since $(this).attr('src') will give "/images/Swatch-TB.jpg".
Instead what you want is the vanilla JS includes.
if ($current_swatch.includes('TB')) {
...
Related
I'm trying to create a simple code where if the user clicks on the gif, it'll switch to another gif repeatedly until it reaches the end of the loop, where the loop restarts. This is the relevant chunk of code:
var storedColoredGif = document.getElementById("coloredGif"); //we grab the gif and store it in storedColoredGif
var onGifClick = function(){
if (document.getElementById("coloredGif").src === "/images/green.gif"){
document.getElementById("coloredGif").src = "/images/blue.gif";
} else if (document.getElementById("coloredGif").src == "/images/blue.gif"){
document.getElementById("coloredGif").src = "/images/yellow.gif";
} else if (document.getElementById("coloredGif").src == "/images/yellow.gif"){
document.getElementById("coloredGif").src = "/images/red.gif";
} else if (document.getElementById("coloredGif").src == "/images/red.gif"){
document.getElementById("coloredGif").src = "/images/green.gif";
}}
storedColoredGif.addEventListener("click", onGifClick);
It's very straightfoward. All of the path names are correct and the gifs source is initially green. The program stores the gif in a variable, then in the function it checks for what the source of the gif is and changes it accordingly when the user clicks on the gif. But nothing happens when I click on it. Am I doing something wrong in my loops? If I had to guess, the problem is that I am correctly changing the source, its just that im never updating the html (but refreshing the page would set the gif to green again because thats what i set in the main html body). What am I doing wrong?
This is how the gif is put in the html (the green.gif is shown fine, its just that its not switching between the gifs when clicked)
<img src="/images/green.gif" id="coloredGif" title="Click me!">
FINAL EDIT: thanks to 2 very helpful users below I was able to figure out that getting the src of the gif actually returns the full domain path, and as such my if statements never progress because theyre always false. Both of their solutions worked.
The solution was to simply work around the fact that checking the src returned the full domain path, instead of just the folders and gif path
The .src will returns a full string of the path: http://example.com/img/... instead of just what you're comparing in your if statement.
Here is a console.log of both .src and .getAttribute output for you to understand:
http://localhost:5501/images/green.gif // Output of .src
/images/green.gif // Output of getAttribute
It should be clearer now about why your if statement wasn't working: you were checking for something that was simply false in all cases. Do not hesitate to console.log values that you're checking when you run into those problems, it, in most of the case, will clear the situation.
Instead, my advice is to uses the .setAttribute to set it, and .getAttribute to get it, which returns the correct path that you're searching for.
Also, you may consider using let & const rather than var.
Here is the code using both methods as stated above.
const storedColoredGif = document.getElementById("coloredGif"); //we grab the gif and store it in storedColoredGif
storedColoredGif.addEventListener("click", () => {
const currentColoredGif = document.getElementById("coloredGif").getAttribute("src")
if (currentColoredGif == "/images/green.gif") {
storedColoredGif.setAttribute("src", "/images/blue.gif")
} else if (currentColoredGif == "/images/blue.gif") {
storedColoredGif.setAttribute("src", "/images/yellow.gif")
} else if (currentColoredGif == "/images/yellow.gif") {
storedColoredGif.setAttribute("src", "/images/red.gif")
} else if (currentColoredGif == "/images/red.gif") {
storedColoredGif.setAttribute("src", "/images/green.gif")
}
})
img src includes the domain as well, for simplicity just check includes, which executes if the string is included in the src
How includes method works - MDN ref
var storedColoredGif = document.getElementById("coloredGif"); //we grab the gif and store it in storedColoredGif
var onGifClick = function() {
if (document.getElementById("coloredGif").src.includes("/images/green.gif")) {
document.getElementById("coloredGif").src = "/images/blue.gif";
} else if (document.getElementById("coloredGif").src.includes("/images/blue.gif")) {
document.getElementById("coloredGif").src = "/images/yellow.gif";
} else if (document.getElementById("coloredGif").src.includes("/images/yellow.gif")) {
document.getElementById("coloredGif").src = "/images/red.gif";
} else if (document.getElementById("coloredGif").src.includes("/images/red.gif")) {
document.getElementById("coloredGif").src = "/images/green.gif";
}
}
storedColoredGif.addEventListener("click", onGifClick);
<img src="/images/green.gif" id="coloredGif" title="Click me!">
I have a JS file that goes to my database and return the value,
The only values that can exist are 0 and 1.
After this I go to an PHP file I invoke this value however I want create a if condition loop to analyze the value of this div for display an image depending of the value.
For example:
if (<div id="last_relay1"></div> = 0) then display IMAGE A
else
if (<div id="last_relay1"></div> = 1) then display IMAGE B
My difficulty is to use the value of as a PHP variable.
//Script to load the value of the current relay
$(document).ready(function(){
setInterval(function(){
$("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update')
}, 1000);
});
//little code to display the value of LAST_RELAY1 for database.
//the values returned possibles are 0 and 1
<div id="last_relay1"></div>
You can use a callback function with .load() to check the text of the DIV after it has been loaded. Use .text() to get the contents of the DIV.
$("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update', function() {
if ($this).text().trim() == "0") {
$("#image").prop("src", "imageA.png");
} else {
$("#image").prop("src", "imageB.png");
}
});
I think what you are looking to do is to send data from the web page (generated by JavaScript) to PHP to decide which image to serve.
The way you framed the question won't help you find a solution (http://xyproblem.info/).
Instead, you will need to either:
preload both image A and image b, and display the one you want in javascript by unhiding it.
Dynamically load the image using PHP by making an XHR request that returns the correct image.
I solved it. I follow the tip provided by Barmar.
I used the following code...
var value = $("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update', function() {
var value_to_test = value.text();
if(value_to_test == 1){
$("#last_relay1").empty();
$('<img src="img/ON.png">').appendTo("#last_relay1"); }
else {
$('<img src="img/OFF.png">').appendTo("#last_relay1");
}
});
So basically my code checks if an HTML element has the value of not 0, if it doesn't sets a timer to change the page title to a notification type of text.
I'm really, really new to JS, so I don't know why this did not work, I tried getElementById("licon liconspan") aswell, nothing.
EDIT: Okay, so I got this to work how I want it, here's the code:
function changeTitle() {
var title = document.title;
var variable = document.querySelector('.liconspan').innerHTML;
if ((variable) !== 0) {
setTimeout(changeTitle, 3000);
document.title = 'You have ' + variable + ' unread messages!';
}
}
changeTitle();
Question though, how can I make it switch back and forth with a title, for example "You got a message" for three seconds then "Page Title" for another three seconds then "You got a message" again, etc..
Since you are using jQuery you can get the element by class using a proper selector and check its value, to change the document title you don't need jQuery.
Alternatively you can use getElementsByClassName:
The Element.getElementsByClassName() method returns a live
HTMLCollection containing all child elements which have all of the
given class names. When called on the document object, the complete
document is searched, including the root node.
Code:
function changeTitle() {
var title = document.title;
if (parseInt($('.liconspan').val()) !== 0 ) {
setTimeout(changeTitle, 3000);
document.title='>'+title;
}
}
changeTitle();
Demo: http://jsfiddle.net/c9p670ra/
I am creating a plugin for a template. After publishing the template to the web, there is an attribute inside an inserted script that I need to get its value and use it in my plugin.
Is there a way to do it with JS/jQuery?
Here is the part of the page in which the attribute is located:
Platform.Utils.initWidget('#skyline', function (elem) {
new Website.tool.Constantin(elem, {
event: 'click',
transitionDuration: 93000
});
});
I need to find a way to search the html and get the value for transitionDuration i.e 93000.
Additional comment:
This code is generated by the template and I have no control on changing how it is formed.
I inspected the html, and the template places the code as a JS code ( "the code" ) somewhere in the body.
So I assumed that there might be a way that the plugin that I am making could be able to read the html, find the attribute and use it to get the same transition duration that the html defines on its elements.
After re-reading and seeing your comments, I assume your template inserts
a script somewhere and you want to get at the transitionDuration with the plugin.
As in
var scripts = document.getElementsByTagName("script"), duration=0;
for (var i=0;i<scripts.length;i++) {
var text = scripts[i].textContent;
if (text.indexOf("transitionDuration") !=-1) {
duration = parseInt(text.split("transitionDuration:")[1],10);
break;
}
}
alert(duration);
<script>
Platform.Utils.initWidget('#skyline', function (elem) {
new Website.tool.Constantin(elem, {
event: 'click',
transitionDuration: 93000
});
});
</script>
You can get CSS values in javascript and jQuery but in this case, is better if you store the value in a variable.
var transDuration = 93000;
Platform.Utils.initWidget('#skyline', function (elem) {
new Website.tool.Constantin(elem, {
event: 'click',
transitionDuration: transDuration
});
});
alert(transDuration);
You can access to the transDuration variable when you need it.
If you need to read a CSS value, take a look at this:
Get a CSS value with JavaScript
Good luck
I have the following code
$(document).ready(function () {
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\]/g, '>');
});
});
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").text(function (i, val) {
return val.replace(/\[/g, "<");
});
});
});
Which with the help of replacing characters in entire document JQuery works wonderfully. However, when the < bracket is inserted, the entire div goes blank. I can replace the [ with anything, but as soon as I put in < everything inside that div disappears. Any idea of what might be going on?
Yes, this is supposed to create a bold (kind of like a bb parser)
Your second replace is using .text() instead of .html(). As a side note, you can also combine the two event handlers.
$(document).ready(function () {
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\]/g, '>').replace(/\[/g, '<');
});
});
});
Here it is in action: http://jsfiddle.net/pbnDP/8/
Pressing the button makes the text go bold.
The obvious security concerns are discussed in the comments on the main post. Don't put this on a site where users can generate the content this is being run on.
It looks like your probably not ending up with Valid HTML and the DOM rendering the html is disposing of any invalid HTML for you.
Theres a few problems with your script - the first it that it promotes dangerous html, your appear not to be doing any form of sanity or blacklist/whitelist checking on the code.
The other issue is your manually naming ASP.NET IDs - this is bad since they can change. Use .ClientID instead.
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\[/g, "<");
});
});
.html might work better then text, and also use class name or clientid to select elements with like John suggested in his answer , that is not good to guess what the browser is going to change the id to.
Pleas check your DOM again, seems like browser either detects the < > as html tag or html aint valid.
Working version: http://jsfiddle.net/pbnDP/
I do know in few programming world including Ruby there is somthing called html_safe you might want to use alongside this.
Hope it helps.