Javascript: Document.URL.indexOf issue - javascript

Hello Guys I have a little issue with document.URL.indexOf in Javascript. I have a lounge page where I want to make the background transparent if there is "lounge" in the URL and I want to make the background different when I am viewing a single lounge but the URL still contains "lounge" cause the full link to a lounge is "lounge/view/1" How can I make it work so when I am in "view" to have the background I want and when I am in lounge to have it transparent.
This is the code I have for now:
if (document.URL.indexOf("lounge") > -1)
{
body.delay(400).css('background-color', 'transparent');
}
else
{
body.delay(400).css('background', '#b4b7b8');
}
I tried adding anothger "else if" saying if indexOF is "view" to go to the one I want but it didn't work.
Any suggestions ?

You can check both if lounge is in the URL and view is not:
if (document.URL.indexOf('lounge') > -1 &&
document.URL.indexOf('view') == -1) {
// your code...
}

How about
var color = document.URL.indexOf('lounge/view') > -1?'#b4b7b8':'transparent';
body.delay(400).css('background', color);
or another colour per view:
var color = 'transparent', url = document.URL;
var views = 'lounge/view';
if (url.indexOf(views) > -1) {
var idx = parseInt(url.split(views)[1],10);
color = ["",'#b4b7b8','#99b7b8','#eeb7b8'][idx]; // view/1, view/2, view/3
}
body.delay(400).css('background', color);

Related

Can't seem to get to the src= to compare image filenames in MonkeyScript

My function is as follows:
function mySound() {
var eventTable = document.querySelector("#eventContent");
var eventCella=eventTable.getElementsByClassName("ago_eventlist_activity");
var eventCellb = eventTable.getElementsByClassName("missionFleet");
for (var i = 0; i < eventTable.rows.length-1; i++) {
var cella = eventCella[i];
var cellb = eventCellb[i];
if (cella.src == "Activity15.gif" && cellb.src == "60a018ae3104b4c7e5af8b2bde5aee.gif")
{theSound = probeSound; oaPlaySound();}
if (cella.img == "Activity15.gif" && cellb.img == "cd360bccfc35b10966323c56ca8aac.gif")
{theSound = attackSound; oaPlaySound();}
if (cella.img == "Activity15.gif" && cellb.img == "575dfbbe877f58d6c09120ffbcaabe.gif") {theSound = attackSoundRIP; oaPlaySound();}
} /* for i */
}
*I can't use ...byid cause it doesn't seem to have one?
I am including a link to the FireFox inspect element so you can see what I can see to try to make this work.
Image of InspectElement:
Any help would be helpful I am just trying to code this for a friend and I really don't know java at all.
Thanks
There is a difference between Java and javascript. I'm guessing you mean javascript since that is what the code appears to be.
There are a few issues with the code
cella.img does not target the image inside of the cell, you'll need to target the image first, or use find the image inside the cell.
var eventCella = eventTable.querySelector(".missionFleet img");
or
var imgb = eventCellb[i].querySelector("img");
Does the ago_eventlist_activity cell even contain an image? There doesn't seem to be one in the screenshot.
Checking the image src needs to include the complete url, unless you use an indexOf...
if (imgb.src.indexOf('60a018ae3104b4c7e5af8b2bde5aee.gif') > -1) {
// do something
}
I hope that helps. Please, the next time you ask a question, include the HTML instead of a screenshot. Or better yet, include a demo (jsFiddle) that shows the problem because it makes it easier for others to help. Not everyone will take the time or make an effort.

Jquery Display round tag image under image issue

I want to add round tag Images(25*25 pixel) on all Image tags in the html Dom.
It works but with my code the position sometimes changes and it often displayed under the Image.
Here is my code:
jQuery("img").each(function() {
var image = jQuery(this);
if ((image.width() >= 512) && (image.width() <= 2048)){
image.parent().css('display', 'inline-block');
var top_pos = image.offset().top+200, left_pos = image.offset().left+150;
image.parent().append('<div class="tag_image first_tag_image1" id="first_draggable1" style="position:absolute;'+'top:'+top_pos+'px;'+'left:'+left_pos+'px;">');
//do something
}
});
Anybody who knows what to do?
If any question please add a comment.
You have to use :before.
For example image.before('//some code')

Using js verification to change background-image

i'm with a little problem. I was building a form in HTML with javascript, but in the inputs, i've used a background-image and a padding in left to make it look better, here its all ok, the problem comes next. I've created this function here:
function verificar_email(email) {
var valor = email.value;
if (valor.length != 0){
if (valor.indexOf('#') >= 1) {
if (valor.indexOf('.') > (valor.indexOf('#') + 1)) {
if (valor.length > (valor.lastIndexOf('.') + 1)) {
email.style.background = "#1abc9c";
email.style.color = "#fefefe";
return true;
}
}
}
}
email.style.background = "#ff0000";
email.style.color = "#fefefe";
return false;
}
When the email input is blank or typed wrong, it's filling my bgimage with bgcolor and making the image dissapear. How can i change my original image to other image i've created without filling with color?
Sorry for my bad english, below i will explain what i'm talking about with some images.
http://imgur.com/a/hkigg - the first image is the error, the second is what it looks like and the final image is what i wanna do.
you can simply set the background color to "transparent" which should stop your background image disappearing

Changing an image source based on an H1 element in the source code or 'location.path'?

I decided to try a different approach to this problem. Instead of relying on a string I thought it would be more efficient for this specific issue to use the function location.path to determine the source of the album-cover. Here's what I only have so far:
The piece of HTML for the image:
<img src="http://static.last.fm/flatness/catalogue/noimage/noalbum_g3.png" width="220" height="220" class="album-cover"/>
The piece of Javascript I have:
var albumCover = document.getElementsByClassName('album-cover') // Get the album cover
var currentLink = location.pathname
var dictionary =
{ // location.pathname : image source for albumCover
'/music/King+Crimson/Red' : 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/Red.jpg',
'/music/King+Crimson/Discipline' : 'http://i1325.photobucket.com/albums/u622/last_fm_projeKct/Last%20FM%20covers/Discipline.jpg'
}
Now here's the piece of the code that's incomplete:
if (currentLink === ''// first part of the dictionary)
{
albumCover.src = '' second part of the dictionary
};
else{};
Any help is welcome and thanks for reading, cheers.
Old Post:
a follow-up on a question I asked recently but I can't seem to be able to change the code to match what I'm looking for. The code occurs on the following website: link
I'm interested in changing the image source in the code below. However, the new image source is to be determined based on what the H1-element of that webpage contains.
<div class="g3 album-cover-wrapper album-cover-wrapper--no-cover " >
<img src="http://static.last.fm/flatness/catalogue/noimage/noalbum_g3.png" width="220" height="220" class="album-cover"/>
<section class="r add-top-margin remove-bottom-margin">
<div class="g4"> </div>
</section>
</div>
Now I thought it would be useful to use 'dictionary-list' like following:
if H1 contains the string 'Discipline'{img.src="newsource.jpg'};
Thanks for taking the time to read this, cheers!
Edit: here's a piece of code I tried but I'm guessing it needs more info for it to actually work.
var headerDef = document.getElementsByTagName('h1'),
var img = document.getElementsByClassName('album-cover');
if (headerDef === 'Red')
{
img.src = "newsource.jpg";
};
else{};
A few examples of how the list will be:
//string in H1 : new image source for the 'album-cover'-class image
'Discipline' : 'http://ecx.images-amazon.com/images/I/41kcnkbxS-L._SL500_AA300_.jpg',
'Red' : 'http://img.noiset.com/images/album/king-crimson-red-4-cd-cover-31985.gif',
etc...
It's a list for which I'd have to manually add each instance of a page having a specific H1-string.
I'd suggest the following:
var map = {
'red': 'oh my gods!',
'blue': 'blue? Really..?'
};
function influenceImage(source, map) {
if (!source || !map) {
return false;
}
else {
var text = source.textContent || source.innerText;
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word) !== -1) {
return map[word];
}
}
}
}
// in real life, with an image use:
// imageNode.src = influenceImage(document.getElementsByTagName('h1')[0], map);
document.getElementById('test').title = influenceImage(document.getElementsByTagName('h1')[0], map);​
JS Fiddle demo.
In the demo I set the title attribute of an a element, but, of course, as noted in the comment simply set the src attribute of an image node.
The above changed, slightly (within the else {...}, to make it a case-insensitive search/match:
var text = (source.textContent || source.innerText).toLowerCase();
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word.toLowerCase()) !== -1) {
return map[word];
}
}
JS Fiddle demo.
And another edit, again within the else {...}, in order to add a default option in case there's no word-match:
var text = (source.textContent || source.innerText).toLowerCase();
for (var word in map) {
if (map.hasOwnProperty(word) && text.indexOf(word.toLowerCase()) !== -1) {
return map[word];
}
}
// we only get here if the `for` loop and the `if` doesn't throw out a match.
return 'default string';
JS Fiddle demo.

How to change button background color 3 times with HTML5 & CSS

I am creating a table of buttons that a internal user can click on individually. I need the buttons to be able to toggle the background from White to Green to Red then back to White .... The user is internal and I can specify that this only works on Chrome. I would like to stick with basic HTML5/CSS3 and Javascript as it is more procedural and my team (we are NOT web page developers) are more likely to be able to maintain it.
Button Elements do not seem to work the same as Text or other elements. I have taken code to change other background colors but it does not work when the element is a button.
My 2 basic blocking issues are:
How do you read the current background color in the onClick()
routine so my code can calculate the next color?
How do you change the style or class of a Button element so that the
background color changes during or when you exit the onClick() routine?
I have seen examples that define 3 different color styles in the CSS file like this:
.make-background-white { background-color: white}
.make-background-green { background-color: green}
.make-background-red { background-color: red}
And I can use these when I initially draw the buttons. But I do not know how to 'read' the current background color in the onClick() routine nor can I change the color.
MORE DETAILS
I read from a database to find all the zip-codes around a store sorted by distance. I create a table of buttons with zip-codes as the text and this can range from 40-600 buttons. The background color shows what zip-codes are not-assigned (white background) and what zip codes are assigned (green background).
Sometimes the user wants to click a few White zip codes to signal that they want to assign that code to the store.
I also want some helper buttons on the side that the user can click to automatically color/assign zip codes to the store with a 30 or 60 or 90 mile radius.
I have a large Javascript Hash/associative array behind the scenes that use the zip-code as the key and this is used to create the buttons, track the distance, track which zip codes are assigned or un-assigned, etc. This is straightforward. Its the dynamically changing the button background that is throwing me off.
I did manage after three days of hacking to make something work by using Jquery with call-backs like this:
$(".btn").click(function() {
if ( $(this).hasClass ('make-background-white') {
$(this).removeClass('make-background-white');
$(this).addClass ('make-background-green');
} else if ( $(this).hasClass('make-background-green') {
// Remove green, add red
} else if () {
// Remove red, add white
}
}
This seems to trigger the button to re-draw with the new background and works by storing a string in the "class" attribute that I can later read and manipulate. It's a call back in the middle of the rest of my more straight-forward Javascript and the other onClick() routines that use "getElementById()" cannot seem to read or manipulate the "class" attribute in the same fashion.
Any help doing the above in Javascript would be appreciated.
If your goal is to implement a background colour-cycling button, in plain JavaScript (in this case without reliance on class-names), then one possible approach is below, though it is, perhaps, over-complicated:
function inArray(needle, haystack) {
if (!needle || !haystack) {
return false;
}
else {
var notFound = -1;
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) {
return i;
}
}
return notFound;
}
}
function colorToggle(el, colors) {
if (!el) {
return false;
}
else {
var colors = colors || [
'rgb(255, 0, 0)',
'rgb(0, 255, 0)',
'rgb(0, 0, 255)'],
wGCS = window.getComputedStyle,
curColor = wGCS(el, null).backgroundColor;
var pos = inArray(curColor, colors);
if (pos > -1 && pos < (colors.length - 1)) {
el.style.backgroundColor = colors[inArray(curColor, colors) + 1];
}
else if (pos > -1 && pos == (colors.length - 1)) {
el.style.backgroundColor = colors[0];
}
}
}
var buttons = document.querySelectorAll('button.colorToggle');
for (var i = 0, len = buttons.length; i < len; i++) {
buttons[i].style.backgroundColor = 'rgb(255, 255, 255)';
buttons[i].onclick = function() {
colorToggle(this, ['rgb(255, 255, 255)','rgb(0, 255, 0)','rgb(255, 0, 0)']);
};
}​
JS Fiddle demo.
Because of your assurance that this is only required to run in Chrome I've tested only in Chromium 18 (since I don't have Windows or Mac in order to test Google Chrome explicitly), and this does seem to do as you require.
References:
window.getComputedStyle.
Do you really need to get the CSS attribute before its change?
An example without this prerequisite:
<html>
<head>
<script type="text/javascript">
var bg_colors = ['red', 'blue', 'green']
function change_bg_color()
{
bg_color = bg_colors.shift();
bg_colors.push(bg_color);
document.getElementById("demo").style.backgroundColor=bg_color;
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>
<button type="button" onclick="change_bg_color()">change background-color</button>
</body>
</html>
If you only need one class name at a time per button you can read/write the classname on click.
$(".btn").click(function() {
var c=this.className;
if(c=='make-background-white' || c=='')this.className='make-background-red';
else if(c=='make-background-red')this.className='make-background-green';
else this.className='make-background-white';
}
This assumes you are starting with white background, either because all buttons start out that way(button, .make-background-white{background-color:white;color:black}), or you set their class attribute.
SUCCESS. I finally found how to access the className attribute with Javascript.
And somehow - setting the className seems to trigger the re-draw of the button.
Below is my function I call with the onClick="zipClick('this_button', 'this_textarea')"
Thank you for all the great responses.
// This function does 2 things:
// Changes the background color of the button
// Calls a REST service
function zipClick (aButtonId, aTextAreaId) {
var lButton = document.getElementById(aButtonId);
var lClassName = lButton.className;
// lClassName should be something like: "btn make-background-yellow"
//alert ("Button Class Start = " + lClassName);
if ( lClassName.indexOf('green') > -1 ) {
lButton.className = 'btn make-background-yellow';
} else if ( lClassName.indexOf('white') > -1) {
lButton.className = 'btn make-background-green';
} else if ( lClassName.indexOf('yellow') > -1 ) {
lButton.className = 'btn make-background-white';
} else {
// Should never get here but fix the class name for the next click
lButton.className = 'btn make-background-white';
}
alert ("old class: " + lClassName + "\nnew class: " + lButton.className);
} // zipClick
You can achieve this by jquery setTimeOut function.By maintaining the hidden value for colors you can toggle the style
<script>
setTimeout(function() {
//code to change style to button
}, 10000);
</script>

Categories